Tuesday, August 30, 2016

Getting KeyCloakContext From ServletRequest

When REST APIs are protected with keycloak authentication, we might need to get user realm in the backend to get some user information.

In the ServletRequestFilter implementation,


public class ApplicationFilter implements Filter {

private Base64 decoder = new Base64(true);

        @Inject
ServletRequestHolder requestHolder;

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
try {
checkAuthentication(req);
....
//TODO
}

/**
* Get the logged in user info from the request.
* @param request
*/
private void checkAuthentication(ServletRequest request) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
KeycloakSecurityContext kContext = (KeycloakSecurityContext) httpServletRequest
.getAttribute(KeycloakSecurityContext.class.getName());
String bearerToken;

if (kContext != null) {

bearerToken = kContext.getTokenString();
String[] jwtToken = bearerToken.split("\\.");
byte[] decodedClaims = decoder.decode(jwtToken[1]);
JSONObject jsonObj = new JSONObject(new String(decodedClaims));
.....
//TODO
}

No comments:

Post a Comment