Logging so as to create a browser session using KeyCloak REST API

Viewed 2666

KeyCloak supports SAML SSO via a KeyCloak login page. After logging in here a browser session is created which allows redirection to client application webpages without further logins. This works. However, I would like to use my own login page and scripts before redirecting users to a client application webpage.

I have been able to use the login credentials of a user (with admin rights) to successfully request an bearer access token from the Keycloak server. But this does not create a browser session.

I have not found any call in the documentation that seems like a session-creating login endpoint (https://documenter.getpostman.com/view/7294517 OR https://documenter.getpostman.com/view/7294517).

Any direction or advice would be appreciated. I work in PHP so far and have been submitting my API calls as cURL requests from PHP, sometimes testing with Postman.

1 Answers

You want to edit and add logic to keycloak page, or use another instead.

First option is the way to go, keycloak allows you to customize login page

Check https://www.baeldung.com/keycloak-custom-login-page

If you still want to create user session from an existing token you'll need to create a new endpoint to get it.

Here you have a useful guide on how to create a custom endpoint with keycloak spi https://medium.com/@gauravwadhone/keycloak-create-custom-rest-api-86e24bff4c1e

And here you have the code i used to get the cookies:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response get() {
    final HttpHeaders headers = session.getContext().getRequestHeaders();
    final String authorization = headers.getHeaderString(HttpHeaders.AUTHORIZATION);
    if(authorization == null) {
        throw new ErrorResponseException(Errors.INVALID_TOKEN, "Null authorization header",
                Response.Status.UNAUTHORIZED);
    }
    final String[] value = authorization.split(" ");
    final String accessToken = value[1];
    final AccessToken token = Tokens.getAccessToken(accessToken, session);
    if (token == null) {
        throw new ErrorResponseException(Errors.INVALID_TOKEN, "Invalid access token", Response.Status.UNAUTHORIZED);
    }
    final RealmModel realm = session.getContext().getRealm();
    final UriInfo uriInfo = session.getContext().getUri();
    final ClientConnection clientConnection = session.getContext().getConnection();
    final UserModel user = session.users().getUserById(token.getSubject(), realm);
    final UserSessionModel userSession = session.sessions().getUserSession(realm, token.getSessionState());
    AuthenticationManager.createLoginCookie(session, realm, user, userSession, uriInfo, clientConnection);
    return Response.noContent().build();
}
Related