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);

ServletRequestHolder requestHolder;

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
try {

* Get the logged in user info from the request.
* @param request
private void checkAuthentication(ServletRequest request) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
KeycloakSecurityContext kContext = (KeycloakSecurityContext) httpServletRequest
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));

No comments:

Post a Comment