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.
getAccount(). getKeycloakSecurityContext(); If there is no refresh token and you only want to access the other token: KeycloakSecurityContext context = token. getAccount().
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).
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
You may also set the principal-attribute
property in the keycloak.json
file of your web app to preferred_username
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With