78

I am working on creating an angular.js web application and looking for how to integrate keycloak into the project. I have read and watched many tutorials and I see that most of them have users logging/registering through the default login page of keycloak which then redirects to the app.

I have designed my own login and registration page which I want to use. How do I use them instead of keycloak default. Are there any API that I can call or may be my backend would do that? I also read there are spring adapters available for keycloak, can I use them ? Any link to any example would be good.

The second question I have is while registering can I add more user details like address, dob, gender in keycloak? Because my registration page requires those information.

krs8888
  • 1,239
  • 4
  • 19
  • 26
  • 1
    Please refer this[https://stackoverflow.com/questions/49313554/access-the-keycloak-api-from-postman/50181199#50181199] for more help – Ankur Singhal May 05 '18 at 10:42
  • 2
    @krs8888 have you found the solution to your original problem ? I am facing the same problem with a reactjs front and a java backend using keycloak. – Emmanuel.B Dec 10 '20 at 16:34
  • 1
    I believe people here don't get the idea. There is no real reason why one SHOULD always use built-in login page. One could get for example the available login methods and use the API for directly initiate the process or do the authentication. This might be on a web page (replacement for built-in login) or even on a mobile app for which the built-in login page is not a proper replacement! – mohamnag Oct 21 '21 at 08:51

7 Answers7

88

Expanding on the API roles

POST to your/keycloak/url/auth/realms/master/protocol/openid-connect/token

with data:

{

    client_id : 'Id_of_your_client',

    username : 'your_username',
    password : '@#$%^&',
    grant_type : "password"

}

will give you the initial access token and refresh token

and

POST to the same URL with

data:

{

    client_id : 'Id_of_your_client',

   // client_secret : 'optional depending on the type of client',

    grant_type : "refresh_token" ,

    refresh_token : refresh_token_you_got_earlier 

}

will give the new refresh and access tokens .These tokens are what keycloak checks for authorization/authentication.

You could make your own login and send the credentials to keycloak via a REST API and once you have the access token , just put it in the header of any ongoing request to a keycloak protected resource as

headers :{

  Authorization : 'Bearer ' +  access_token_you_got

}
v.ladynev
  • 19,275
  • 8
  • 46
  • 67
UchihaItachi
  • 2,602
  • 14
  • 21
  • Please help something am missing. When i try the above facing this issue. Access to XMLHttpRequest at 'http://34.125.161.210:8180/realms/frtest/protocol/openid-connect/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. – Abdul Aug 01 '22 at 13:22
  • The same url with the same parameters am able to access from postman, and am getting access token as well. Please help – Abdul Aug 01 '22 at 13:23
  • Use POST request instead of GET. – NaN Mar 21 '23 at 13:56
  • How do we update the `next-auth` session with the token we received from keycloak? – shAkur Jun 21 '23 at 16:52
47

3 steps:

  1. In the keycloak/themes/ directory create folder with name eg. myTheme.

 directory structure

  1. In the myTheme folder place your custom login page

    (the structure must be same as base or keycloak themes, my advice is to copy the base theme, rename it and customize it).

  2. Go to the admin console of keycloak into Realm Settings > Themes > Login Theme and select myTheme.

enter image description here

Community
  • 1
  • 1
Tomas Marik
  • 4,053
  • 3
  • 31
  • 62
  • 34
    While good, the problem with this advice is that the base theme is incredibly complex, especially the templating. We've found that new releases of Keycloak require the themes to be updated, and they inject a lot of HTML magic which interferes with the design. What would be ideal is to know what we need to POST and what we need to process in a GET, in order to write a login page from scratch. That way, our designers can give us the HTML/CSS and we can work from there. – Doctor Eval Mar 15 '18 at 00:29
  • 1
    Great answer. It works. Is there a possibility to customize a login page per client, not per realm? – Dmitriy Popov Jan 26 '21 at 15:29
  • Yes there is option in client setting for keycloak themes, set there – Deepak N Jan 19 '23 at 07:19
4

Use the below code if you want to hit the Keycloak login page through Java and get the response:

String uri = "http://localhost:7080/auth/realms/{RealmName}/protocol/openid-connect/token";

            HttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(uri);
            post.setHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
            List<BasicNameValuePair> urlParameters = new ArrayList<BasicNameValuePair>();
            urlParameters.add(new BasicNameValuePair("grant_type", "password"));
            urlParameters.add(new BasicNameValuePair("client_id", {ClientName}));
            urlParameters.add(new BasicNameValuePair("username", {UserName}));
            urlParameters.add(new BasicNameValuePair("password", {Password}));
            post.setEntity(new UrlEncodedFormEntity(urlParameters));
            HttpResponse response = client.execute(post);
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line1 = "";
            while ((line1 = rd.readLine()) != null) {
                result.append(line1);
            }
            System.out.println(result);

If your username and password are valid, response.getStatusLine().getStatusCode() will give the value as HTTP 200 along with AccessToken and RefreshToken. Otherwise response.getStatusLine().getStatusCode() will give the value as HTTP 403 and data as: {"error":"invalid_grant","error_description":"Invalid user credentials"}

Yuri
  • 4,254
  • 1
  • 29
  • 46
whywake
  • 880
  • 10
  • 29
3
  • You probably should stick with the Keycloack's forms. They bring nice features (SSO, pw reset, etc.) and are fully customizable (via themes). However, there it is possible to obtain the Access Token via so called Direct Access Grant. It can be done via Keycloak REST API.
  • Storing the custom user info (gender, job, etc.) is done by User Attributes

Both topics are more or less covered in the official Keycloak Docs.

Yuri
  • 4,254
  • 1
  • 29
  • 46
  • 1
    Is it also possible to create/register a user from a native mobile app?I tried this endpoint: auth/admin/realms/{realm}/users but it gives me a 401 error. I think it's an endpoint to create a user AFTER you have logged in as an admin. – Francis Zabala Sep 15 '16 at 09:55
  • 1
    User self-registration has to be enabled in the realm settings in advance. However, I am not sure how to perform a self-registration via a Keycloak API. – Yuri Sep 16 '16 at 09:21
  • 1
    thanks. It is possible but I have to extend Keycloak. Problem with extending is you can't test your code before you deploy it to Keycloak. Pretty sure the smart guys at jboss will eventually create an "SDK" of some sort. – Francis Zabala Sep 17 '16 at 06:25
1

Put your login theme in keycloak themes directory and by admin loging change login theme setting and choose your theme from drop-down. Your login theme must in keycloak default theme formate so to create your's please refer keycloak default theme and design your's according to that.

You can refer following Keycloak theme configuration

Aman Jaiswal
  • 1,084
  • 2
  • 18
  • 36
0

From the docs, it seems that you extend themes or override individual resources (templates, stylesheets, etc.): https://www.keycloak.org/docs/latest/server_development/#creating-a-theme

Regarding the additional user details, again from the docs: https://www.keycloak.org/docs/latest/server_development/#_custom_user_attributes

0

You can write your custom inline css in

keycloak/themes/base/template.ftl

And

keycloak/themes/base/login.ftl

then you will be able to use keycloak login page but ui like project login page