Use Keycloak Admin REST APIs with legacy applications



As I mentioned in the previous post, Keycloak is the most commonly used security framework in modern applications. But somehow you may have to use Keycloak with your legacy applications also. Here I am going to use three Keycloak Admin REST APIs for the following flows.  
  1. Get a Keyclaok bearer token
  2. Check the username exists or not
  3. Create a new user in Keycloak database
Older applications are built using very older frameworks such as Struts and older Java versions. So here I used very basic Java libraries to call Keycloak APIs with simple coding methods. You need to run the Keyclaok server and check all configurations such as client id, grant type, port, realm... etc. For more info, please visit Integrate Keycloak with Spring Boot 

Get a Keycloak bearer token


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

public class GetToken {

    public static void main(String[] args) throws IOException {
        new GetToken().getBearerToken();
    }

    public String getBearerToken() throws IOException{

        String client_id = "login-app";
        String grant_type = "client_credentials";
        String client_secret = "6b574a0b-6624-4d7a-9ac6-485c1fdcc9e0";
        String port = "8081";
        String realm = "api";
        String server = "localhost";
        String content_type = "application/x-www-form-urlencoded";
        String method_type = "POST";
        String encode_type = "UTF-8";

        URL url = new URL("http://"+ server +":"+ port +"/auth/realms/"+ realm +"/protocol/openid-connect/token");

        Map params = new LinkedHashMap();
        params.put("client_id", client_id);
        params.put("grant_type", grant_type);
        params.put("client_secret", client_secret);

        StringBuilder postData = new StringBuilder();
        for(Map.Entry param : params.entrySet()){
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), encode_type));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), encode_type));
        }

        byte[] postDataBytes = postData.toString().getBytes(encode_type);

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod(method_type);
        conn.setRequestProperty("Content-Type", content_type);
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encode_type));
        String line;
        StringBuilder result = new StringBuilder();

        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        String response = result.toString();

        String[] array = response.split(",");
        String[] accessToken = array[0].split(":");
        String token = accessToken[1].replace("\"","");

        System.out.println(token);

        return token;
    }
}

Before we use any Keycloak REST API, we need to get the access token to call any Admin REST API. In this class, getBearerToken() method will return only the access token. This token can be used in the Authorization header in the request that you need. I have mentioned all properties in the same method, but according to your application, you can import properties in the way you do it. 



Check the username exists or not


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class CheckUsername {

    public static void main(String args[]) throws IOException {
       new CheckUsername().checkUsername("user1");
    }

    public Boolean checkUsername(String username) throws IOException {

        String port = "8081";
        String realm = "api";
        String server = "localhost";
        String content_type = "application/json";
        String method_type = "GET";
        String encode_type = "UTF-8";
        String bearerToken = new GetToken().getBearerToken();

        URL url = new URL("http://" + server + ":" + port + "/auth/admin/realms/" + realm + "/users?username=" + username);

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod(method_type);
        conn.setRequestProperty("Content-Type", content_type);
        conn.setRequestProperty("Authorization", "Bearer " + bearerToken.trim());
        conn.setDoOutput(true);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encode_type));
        String line;
        StringBuilder result = new StringBuilder();

        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        String response = result.toString();

        if(response.contentEquals("[]")){
            return false;
        }else {
            return true;
        }
    }
}

To use this API, we need to get the Keycloak bearer token. In this example, I have called the previous method to get the token (new GetToken().getBearerToken()) and I pass the username as a parameter in the URL.


Create a new user in Keycloak database


import com.google.gson.Gson;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class CreateNewUser implements Serializable {

    public static void main(String args[]) throws IOException {
        new CreateNewUser().createUser("user1", "üser1@gmail.com", "user1");
    }


    public int createUser(String username, String email, String password) throws IOException {

        String grant_type = "password";
        String port = "8081";
        String realm = "api";
        String server = "localhost";
        String content_type = "application/json";
        String method_type = "POST";
        String encode_type = "UTF-8";
        String bearerToken = new GetToken().getBearerToken();
        int responseCode = 0;

        ArrayList arrayList = new ArrayList();

        Credentials credentials = new Credentials();
        if (grant_type != null) {
            credentials.setType(grant_type);
        }
        credentials.setTemporary(true);
        if (password != null) {
            credentials.setValue(password);
        }
        arrayList.add(credentials);

        PostBody postBody = new PostBody();
        if (username != null) {
            postBody.setUsername(username);
        }
        if (email != null) {
            postBody.setEmail(email);
        }
        postBody.setCredentials(arrayList);

        try {

            Gson gson = new Gson();
            String jsonString = gson.toJson(postBody);

            URL url = new URL("http://" + server + ":" + port + "/auth/admin/realms/" + realm + "/users/");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(method_type);
            conn.setRequestProperty("Content-Type", content_type);
            conn.setRequestProperty("Accept", content_type);
            conn.setDoOutput(true);
            conn.setRequestProperty("Authorization", "Bearer " + bearerToken.trim());

            OutputStream os = conn.getOutputStream();
            byte[] input = jsonString.getBytes(encode_type);
            os.write(input, 0, input.length);


            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), encode_type));
            StringBuilder response = new StringBuilder();
            String responseLine = null;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            responseCode = conn.getResponseCode();

            System.out.println(responseCode);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return responseCode;
    }


    public class PostBody implements Serializable {
        private String email;
        private String username;
        private ArrayList credentials;

        public PostBody() {
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public ArrayList getCredentials() {
            return credentials;
        }

        public void setCredentials(ArrayList credentials) {
            this.credentials = credentials;
        }
    }

    public class Credentials implements Serializable {
        private String value;
        private Boolean temporary;
        private String type;

        public Credentials() {
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public Boolean getTemporary() {
            return temporary;
        }

        public void setTemporary(Boolean temporary) {
            this.temporary = temporary;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }
    }
}


According to the Keycloak documentation, you can add or change any property you want. Here I use some very simple properties. I used the Gson library, you can use any library which suited to your requirements. 

These are just very simple examples that show, how to use Keycloak REST APIs in your older applications. You can adjust it according to the requirement.  

Please look at the Keycloak official documentation for more information about the Admin REST APIs and more. 


Use Keycloak Admin REST APIs with legacy applications Use Keycloak Admin REST APIs with legacy applications Reviewed by Ravi Yasas on 9:31 PM Rating: 5

35 comments:

  1. I just could not depart your website prior to suggesting that I really enjoyed the usual information a person provide for your guests?
    Is going to be again ceaselessly in order to check up on new posts

    ReplyDelete
  2. hey there and thank you for your information – I've certainly picked up something new from right here.
    I did however expertise some technical issues using this web site, since I experienced to reload the site
    a lot of times previous to I could get it to load properly.
    I had been wondering if your web hosting is OK?

    Not that I'm complaining, but sluggish loading instances
    times will very frequently affect your placement in google
    and can damage your high-quality score if ads and marketing with
    Adwords. Anyway I'm adding this RSS to my e-mail and can look out for a lot more of your respective fascinating content.
    Make sure you update this again soon.

    ReplyDelete
  3. hey there and thank you for your information – I have definitely picked up something
    new from right here. I did however expertise some technical issues using this website,
    since I experienced to reload the site many times previous to I could get it to load correctly.
    I had been wondering if your hosting is OK? Not that I
    am complaining, but slow loading instances times will sometimes affect
    your placement in google and can damage your high quality score if advertising and marketing with Adwords.
    Anyway I'm adding this RSS to my e-mail and could look out for much more of your respective exciting content.
    Make sure you update this again soon.

    ReplyDelete
  4. It's fantastic that you are getting ideas from this piece of writing as well as from our discussion made at this place.

    ReplyDelete
  5. This page definitely has all of the info I wanted about this subject and didn't know who to ask.

    ReplyDelete
  6. Hey there! I could have sworn I've been to this website before but after reading through some of the post
    I realized it's new to me. Nonetheless, I'm definitely glad I
    found it and I'll be book-marking and checking back frequently!

    ReplyDelete
  7. I’m not that much of a online reader to be honest but your
    blogs really nice, keep it up! I'll go ahead and bookmark your website to come back down the road.
    Cheers

    ReplyDelete
  8. Wonderful goods from you, man. I've remember your stuff previous to and you're just too excellent.
    I really like what you've received here, really
    like what you're stating and the way in which wherein you say it.
    You're making it entertaining and you continue to
    care for to keep it wise. I cant wait to read far more from
    you. That is really a great web site.

    ReplyDelete
  9. Excellent article. Keep writing such kind of information on your site.

    Im really impressed by your blog.
    Hey there, You've done an incredible job. I will definitely digg it
    and for my part recommend to my friends. I'm sure they will be benefited from this
    website.

    ReplyDelete
  10. My partner and I stumbled over here from a different web address
    and thought I should check things out. I like what I see so now i'm following you.
    Look forward to looking at your web page yet again.

    ReplyDelete
  11. This website was... how do I say it? Relevant!!
    Finally I've found something that helped me. Thanks a lot!

    ReplyDelete
  12. Neat blog! Is your theme custom made or did you download it from somewhere?
    A theme like yours with a few simple tweeks would really make my blog stand out.
    Please let me know where you got your theme. With thanks

    ReplyDelete
  13. If you desire to grow your know-how just keep visiting this website and be updated
    with the newest news update posted here.

    ReplyDelete
  14. WOW just what I was looking for. Came here by searching for Bandar Ceme

    ReplyDelete
  15. It's truly a nice and helpful piece of information. I am satisfied that you
    shared this useful info with us. Please stay us up to date like this.

    Thank you for sharing.

    ReplyDelete
  16. Hi there! I know this is kinda off topic but I'd figured I'd ask.

    Would you be interested in trading links or maybe guest authoring a blog article or vice-versa?
    My website discusses a lot of the same subjects as yours and
    I believe we could greatly benefit from each other.
    If you happen to be interested feel free to shoot me an email.
    I look forward to hearing from you! Excellent blog
    by the way!

    ReplyDelete
  17. I got this web page from my buddy who shared with me on the topic of this site and at the moment this time I am visiting this web site and reading very informative content at this time.

    ReplyDelete
  18. It is perfect time to make some plans for the future and it
    is time to be happy. I have read this post and if I could I
    want to suggest you few interesting things or advice. Maybe you can write next articles referring to this article.
    I wish to read more things about it!

    ReplyDelete
  19. Write more, thats all I have to say. Literally, it seems as though you relied
    on the video to make your point. You obviously
    know what youre talking about, why throw away your intelligence on just posting videos to your weblog when you could
    be giving us something enlightening to read?

    ReplyDelete
  20. Yes! Finally someone writes about Judi Online via Pulsa.

    ReplyDelete
  21. It's the best time to make some plans for the future and it is
    time to be happy. I have read this post and if I could I
    desire to suggest you few interesting things or suggestions.
    Maybe you can write next articles referring to this article.
    I desire to read even more things about it!

    ReplyDelete
  22. I used to be able to find good info from your blog articles.

    ReplyDelete
  23. Hi are using Wordpress for your blog platform?

    I'm new to the blog world but I'm trying to get started and set up my own. Do you need any coding knowledge to make
    your own blog? Any help would be greatly appreciated!

    ReplyDelete
  24. I like it when folks get together and share opinions.
    Great site, keep it up!

    ReplyDelete
  25. Wow, amazing blog layout! How long have you been blogging for?
    you made blogging look easy. The overall look of your site is fantastic, let alone the
    content!

    ReplyDelete
  26. Hi there, I enjoy reading through your article post. I like to
    write a little comment to support you.

    ReplyDelete
  27. I enjoy what you guys tend to be up too. This
    kind of clever work and reporting! Keep up the amazing works guys I've included you guys to my personal
    blogroll.

    ReplyDelete
  28. I'm extremely inspired with your writing skills and also with the structure on your blog.
    Is this a paid topic or did you customize it your self? Either way keep up the excellent high quality writing,
    it's rare to look a nice weblog like this one today..

    ReplyDelete
  29. Thanks , I have just been searching for info about this subject for ages and yours is the greatest I have discovered till now.

    However, what in regards to the bottom line? Are you certain about the supply?

    ReplyDelete
  30. Whoa! This blog looks exactly like my old one! It's on a completely
    different subject but it has pretty much the same page layout
    and design. Wonderful choice of colors!

    ReplyDelete
  31. This page really has all the information I wanted concerning this subject and didn't know
    who to ask.

    ReplyDelete
  32. Hello to all, the contents existing at this site are genuinely remarkable for
    people experience, well, keep up the good work fellows.

    ReplyDelete
  33. I got this web site from my friend who shared with me on the topic of this website and at the
    moment this time I am browsing this site and reading very informative articles or reviews here.

    ReplyDelete
  34. Hello There. I found your blog using msn. This is a really well written article.
    I will be sure to bookmark it and return to read more of your
    useful info. Thanks for the post. I'll certainly
    return.

    ReplyDelete
  35. An intriguing discussion is worth comment.
    I think that you need to write more about this subject matter, it might
    not be a taboo subject but typically people do not speak about these subjects.
    To the next! Cheers!!

    ReplyDelete

Powered by Blogger.