Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch Logged In Username in a webapp secured with Keycloak

Tags:

I have secured an enterprise application with Keycloak using standard wildfly based Keycloak adapters. Issue that I am facing is that the rest web services when invoked, needs to know the username that is currently logged in. How do I get the logged in user information from Keycloak?

I tried using SecurityContext , WebListener etc. But none of them are able to give me the required details.

like image 758
aksappy Avatar asked Aug 06 '15 19:08

aksappy


People also ask

How do I get KeycloakSecurityContext?

getAccount(). getKeycloakSecurityContext(); If there is no refresh token and you only want to access the other token: KeycloakSecurityContext context = token. getAccount().

How do you get a Keycloak access token?

Navigate to the Postman Authorization tab of your request. From the Type dropdown menu, select OAuth 2.0: Click on the Get New Access Token button that will open a dialog box for configuring the identity server (Keycloak in our case).


2 Answers

You get all user information from the security context.

Example:

public class Greeter {    @Context   SecurityContext sc;    @GET   @Produces(MediaType.APPLICATION_JSON)   public String sayHello() {      // this will set the user id as userName     String userName = sc.getUserPrincipal().getName();      if (sc.getUserPrincipal() instanceof KeycloakPrincipal) {       KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>)  sc.getUserPrincipal();        // this is how to get the real userName (or rather the login name)       userName = kp.getKeycloakSecurityContext().getIdToken().getPreferredUsername();     }      return "{ message : \"Hello " + userName + "\" }"; } 

For the security context to be propagated you have to have a security domain configured as described in the: JBoss/Wildfly Adapter configuration

like image 199
sebplorenz Avatar answered Oct 16 '22 02:10

sebplorenz


You may also set the principal-attribute property in the keycloak.json file of your web app to preferred_username.

like image 26
user3569718 Avatar answered Oct 16 '22 01:10

user3569718