org.keycloak.KeycloakSecurityContext Java Examples

The following examples show how to use org.keycloak.KeycloakSecurityContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VertxHttpFacade.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@Override
public KeycloakSecurityContext getSecurityContext() {
    SecurityIdentity identity = QuarkusHttpUser.getSecurityIdentityBlocking(routingContext, null);
    if (identity == null) {
        return null;
    }
    TokenCredential credential = identity.getCredential(AccessTokenCredential.class);

    if (credential == null) {
        return null;
    }

    String token = credential.getToken();

    try {
        return new KeycloakSecurityContext(token, new JWSInput(token).readJsonContent(AccessToken.class), null, null);
    } catch (JWSInputException e) {
        throw new RuntimeException("Failed to create access token", e);
    }
}
 
Example #2
Source File: CatalinaRequestAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void completeOAuthAuthentication(final KeycloakPrincipal<RefreshableKeycloakSecurityContext> skp) {
    final RefreshableKeycloakSecurityContext securityContext = skp.getKeycloakSecurityContext();
    final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
    OidcKeycloakAccount account = new OidcKeycloakAccount() {

        @Override
        public Principal getPrincipal() {
            return skp;
        }

        @Override
        public Set<String> getRoles() {
            return roles;
        }

        @Override
        public KeycloakSecurityContext getKeycloakSecurityContext() {
            return securityContext;
        }

    };

    request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);
    this.tokenStore.saveAccountInfo(account);
}
 
Example #3
Source File: JettySessionTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void checkCurrentToken() {
    if (request.getSession(false) == null) return;
    RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) request.getSession().getAttribute(KeycloakSecurityContext.class.getName());
    if (session == null) return;

    // just in case session got serialized
    if (session.getDeployment() == null) session.setCurrentRequestInfo(deployment, this);

    if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) return;

    // FYI: A refresh requires same scope, so same roles will be set.  Otherwise, refresh will fail and token will
    // not be updated
    boolean success = session.refreshExpiredToken(false);
    if (success && session.isActive()) return;

    // Refresh failed, so user is already logged out from keycloak. Cleanup and expire our session
    request.getSession().removeAttribute(KeycloakSecurityContext.class.getName());
    request.getSession().invalidate();
}
 
Example #4
Source File: SpringSecurityCookieTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void checkCurrentToken() {
    final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal =
            checkPrincipalFromCookie();
    if (principal != null) {
        final RefreshableKeycloakSecurityContext securityContext =
                principal.getKeycloakSecurityContext();
        KeycloakSecurityContext current = ((OIDCHttpFacade) facade).getSecurityContext();
        if (current != null) {
            securityContext.setAuthorizationContext(current.getAuthorizationContext());
        }
        final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
        final OidcKeycloakAccount account =
                new SimpleKeycloakAccount(principal, roles, securityContext);
        SecurityContextHolder.getContext()
                .setAuthentication(new KeycloakAuthenticationToken(account, false));
    } else {
        super.checkCurrentToken();
    }
    cookieChecked = true;
}
 
Example #5
Source File: KeycloakLoggedInUser.java    From pnc with Apache License 2.0 6 votes vote down vote up
public KeycloakLoggedInUser(HttpServletRequest httpServletRequest) {
    if (httpServletRequest == null) {
        throw new NullPointerException();
    }
    try {
        KeycloakSecurityContext keycloakSecurityContext = (KeycloakSecurityContext) httpServletRequest
                .getAttribute(KeycloakSecurityContext.class.getName());
        if (keycloakSecurityContext == null) {
            handleAuthenticationProblem("KeycloakSecurityContext not available in the HttpServletRequest.");
        } else {
            this.auth = keycloakSecurityContext.getToken();
            this.tokenString = keycloakSecurityContext.getTokenString();
        }
    } catch (NoClassDefFoundError ncdfe) {
        handleAuthenticationProblem(ncdfe.getMessage(), ncdfe);
    }
}
 
Example #6
Source File: FilterRequestAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void completeOAuthAuthentication(final KeycloakPrincipal<RefreshableKeycloakSecurityContext> skp) {
    final RefreshableKeycloakSecurityContext securityContext = skp.getKeycloakSecurityContext();
    final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
    OidcKeycloakAccount account = new OidcKeycloakAccount() {

        @Override
        public Principal getPrincipal() {
            return skp;
        }

        @Override
        public Set<String> getRoles() {
            return roles;
        }

        @Override
        public KeycloakSecurityContext getKeycloakSecurityContext() {
            return securityContext;
        }

    };

    request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);
    this.tokenStore.saveAccountInfo(account);
}
 
Example #7
Source File: AuthzClientRequestFactory.java    From devconf2019-authz with Apache License 2.0 6 votes vote down vote up
@Override
protected void postProcessHttpRequest(HttpUriRequest request) {
    KeycloakSecurityContext context = this.getKeycloakSecurityContext();

    // TODO: Ideally should do it all automatically by some provided adapter/utility
    String currentRpt = rptStore.getRpt(context);
    if (currentRpt == null) {
        // Fallback to access token
        currentRpt = context.getTokenString();
    } else {
        AccessToken parsedRpt = rptStore.getParsedRpt(context);
        if (!parsedRpt.isActive(10)) {
            // Just delete RPT and use accessToken instead. TODO: Will be good to have some "built-in" way to refresh RPT for clients
            log.info("Deleting expired RPT. Will need to obtain new when needed");
            rptStore.deleteCurrentRpt(servletRequest);
            currentRpt = context.getTokenString();
        }
    }

    request.setHeader(AUTHORIZATION_HEADER, "Bearer " + currentRpt);
}
 
Example #8
Source File: ProductDatabaseClient.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static List<String> getProducts(HttpServletRequest req) throws Failure {
    KeycloakSecurityContext session = (KeycloakSecurityContext)req.getAttribute(KeycloakSecurityContext.class.getName());

    HttpClient client = new DefaultHttpClient();
    try {
        HttpGet get = new HttpGet(UriUtils.getOrigin(req.getRequestURL().toString()) + "/database/products");
        get.addHeader("Authorization", "Bearer " + session.getTokenString());
        try {
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new Failure(response.getStatusLine().getStatusCode());
            }
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            try {
                return JsonSerialization.readValue(is, TypedList.class);
            } finally {
                is.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #9
Source File: ElytronCookieTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void logout(boolean glo) {
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = CookieTokenStore.getPrincipalFromCookie(this.httpFacade.getDeployment(), this.httpFacade, this);

    if (principal == null) {
        return;
    }

    CookieTokenStore.removeCookie(this.httpFacade.getDeployment(), this.httpFacade);

    if (glo) {
        KeycloakSecurityContext ksc = (KeycloakSecurityContext) principal.getKeycloakSecurityContext();

        if (ksc == null) {
            return;
        }

        KeycloakDeployment deployment = httpFacade.getDeployment();

        if (!deployment.isBearerOnly() && ksc != null && ksc instanceof RefreshableKeycloakSecurityContext) {
            ((RefreshableKeycloakSecurityContext) ksc).logout(deployment);
        }
    }
}
 
Example #10
Source File: KeycloakAuthenticationProcessingFilterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    request = spy(new MockHttpServletRequest());
    request.setRequestURI("http://host");
    filter = new KeycloakAuthenticationProcessingFilter(authenticationManager);
    keycloakFailureHandler = new KeycloakAuthenticationFailureHandler();

    filter.setApplicationContext(applicationContext);
    filter.setAuthenticationSuccessHandler(successHandler);
    filter.setAuthenticationFailureHandler(failureHandler);

    when(applicationContext.getBean(eq(AdapterDeploymentContext.class))).thenReturn(adapterDeploymentContext);
    when(adapterDeploymentContext.resolveDeployment(any(HttpFacade.class))).thenReturn(keycloakDeployment);
    when(keycloakAccount.getPrincipal()).thenReturn(
            new KeycloakPrincipal<KeycloakSecurityContext>(UUID.randomUUID().toString(), keycloakSecurityContext));


    filter.afterPropertiesSet();
}
 
Example #11
Source File: ServletSessionTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void logout() {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
    req.removeAttribute(KeycloakUndertowAccount.class.getName());
    req.removeAttribute(KeycloakSecurityContext.class.getName());
    HttpSession session = req.getSession(false);
    if (session == null) return;
    try {
        KeycloakUndertowAccount account = (KeycloakUndertowAccount) session.getAttribute(KeycloakUndertowAccount.class.getName());
        if (account == null) return;
        session.removeAttribute(KeycloakSecurityContext.class.getName());
        session.removeAttribute(KeycloakUndertowAccount.class.getName());
    } catch (IllegalStateException ise) {
        // Session may be already logged-out in case that app has adminUrl
        log.debugf("Session %s logged-out already", session.getId());
    }
}
 
Example #12
Source File: HolaResource.java    From hola with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/hola-secured")
@Produces("text/plain")
@ApiOperation("Returns a message that is only available for authenticated users")
public String holaSecured() {
    // this will set the user id as userName
    String userName = securityContext.getUserPrincipal().getName();

    if (securityContext.getUserPrincipal() instanceof KeycloakPrincipal) {
        @SuppressWarnings("unchecked")
        KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) securityContext.getUserPrincipal();

        // this is how to get the real userName (or rather the login name)
        userName = kp.getKeycloakSecurityContext().getToken().getName();
    }
    return "This is a Secured resource. You are logged as " + userName;

}
 
Example #13
Source File: SecurityContextServletExtension.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public void handleDeployment(DeploymentInfo info, ServletContext context) {
    info.addThreadSetupAction(new KeycloakThreadSetupHandler());

    info.addInnerHandlerChainWrapper(next -> exchange -> {
        KeycloakSecurityContext c = exchange.getAttachment(OIDCUndertowHttpFacade.KEYCLOAK_SECURITY_CONTEXT_KEY);
        if (c != null) {
            KeycloakSecurityContextAssociation.associate(c);
        }
        try {
            next.handleRequest(exchange);
        } finally {
            KeycloakSecurityContextAssociation.disassociate();
        }
    });
}
 
Example #14
Source File: MultiTenantServlet.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    String realm = req.getPathInfo().split("/")[1];
    if (realm.contains("?")) {
        realm = realm.split("\\?")[0];
    }
    
    if (req.getPathInfo() != null && req.getPathInfo().contains("logout")) {
        req.logout();
        resp.sendRedirect(req.getContextPath() + "/" + realm);
        return;
    }
    
    resp.setContentType("text/html");
    PrintWriter pw = resp.getWriter();
    KeycloakSecurityContext context = (KeycloakSecurityContext)req.getAttribute(KeycloakSecurityContext.class.getName());

    pw.print("Username: ");
    pw.println(context.getIdToken().getPreferredUsername());

    pw.print("<br/>Realm: ");
    pw.println(context.getRealm());

    pw.flush();
}
 
Example #15
Source File: JettyCookieTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isCached(RequestAuthenticator authenticator) {
    // Assuming authenticatedPrincipal set by previous call of checkCurrentToken() during this request
    if (authenticatedPrincipal != null) {
        log.debug("remote logged in already. Establish state from cookie");
        RefreshableKeycloakSecurityContext securityContext = authenticatedPrincipal.getKeycloakSecurityContext();

        if (!securityContext.getRealm().equals(deployment.getRealm())) {
            log.debug("Account from cookie is from a different realm than for the request.");
            return false;
        }

        securityContext.setCurrentRequestInfo(deployment, this);

        request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);

        JettyRequestAuthenticator jettyAuthenticator = (JettyRequestAuthenticator) authenticator;
        KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = AdapterUtils.createPrincipal(deployment, securityContext);
        jettyAuthenticator.principal = principal;
        return true;
    } else {
        return false;
    }
}
 
Example #16
Source File: ElytronSessionTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void saveAccountInfo(OidcKeycloakAccount account) {
    HttpScope session = this.httpFacade.getScope(Scope.SESSION);

    if (!session.exists()) {
        session.create();
        session.registerForNotification(httpScopeNotification -> {
            if (!httpScopeNotification.isOfType(HttpScopeNotification.SessionNotificationType.UNDEPLOY)) {
                HttpScope invalidated = httpScopeNotification.getScope(Scope.SESSION);

                if (invalidated != null) {
                    invalidated.setAttachment(ElytronAccount.class.getName(), null);
                    invalidated.setAttachment(KeycloakSecurityContext.class.getName(), null);
                }
            }
        });
    }

    session.setAttachment(ElytronAccount.class.getName(), account);
    session.setAttachment(KeycloakSecurityContext.class.getName(), account.getKeycloakSecurityContext());

    HttpScope scope = this.httpFacade.getScope(Scope.EXCHANGE);

    scope.setAttachment(KeycloakSecurityContext.class.getName(), account.getKeycloakSecurityContext());
}
 
Example #17
Source File: JettySessionTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isCached(RequestAuthenticator authenticator) {
    if (request.getSession(false) == null || request.getSession().getAttribute(KeycloakSecurityContext.class.getName()) == null)
        return false;
    log.debug("remote logged in already. Establish state from session");

    RefreshableKeycloakSecurityContext securityContext = (RefreshableKeycloakSecurityContext) request.getSession().getAttribute(KeycloakSecurityContext.class.getName());
    if (!deployment.getRealm().equals(securityContext.getRealm())) {
        log.debug("Account from cookie is from a different realm than for the request.");
        return false;
    }

    securityContext.setCurrentRequestInfo(deployment, this);
    request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);

    JettyRequestAuthenticator jettyAuthenticator = (JettyRequestAuthenticator) authenticator;
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = AdapterUtils.createPrincipal(deployment, securityContext);
    jettyAuthenticator.principal = principal;
    restoreRequest();
    return true;
}
 
Example #18
Source File: AbstractUser.java    From keycloak-dropwizard-integration with Apache License 2.0 5 votes vote down vote up
public AbstractUser(HttpServletRequest request, KeycloakSecurityContext securityContext,
                    KeycloakConfiguration keycloakConfiguration) {
    this.request = request;
    this.securityContext = securityContext;

    this.roles = selectRolesToApply(keycloakConfiguration);
}
 
Example #19
Source File: JettyRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void completeBearerAuthentication(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal, String method) {
    this.principal = principal;
    RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext();
    Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
    if (log.isDebugEnabled()) {
        log.debug("Completing bearer authentication. Bearer roles: " + roles);
    }
    request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);
}
 
Example #20
Source File: AbstractKeycloakAuthenticatorValve.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void logoutInternal(Request request) {
    KeycloakSecurityContext ksc = (KeycloakSecurityContext)request.getAttribute(KeycloakSecurityContext.class.getName());
    if (ksc != null) {
        CatalinaHttpFacade facade = new OIDCCatalinaHttpFacade(request, null);
        KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
        if (ksc instanceof RefreshableKeycloakSecurityContext) {
            ((RefreshableKeycloakSecurityContext) ksc).logout(deployment);
        }

        AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment);
        tokenStore.logout();
        request.removeAttribute(KeycloakSecurityContext.class.getName());
    }
    request.setUserPrincipal(null);
}
 
Example #21
Source File: SpringSecurityRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void completeOAuthAuthentication(final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {

    final RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext();
    final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
    final OidcKeycloakAccount account = new SimpleKeycloakAccount(principal, roles, securityContext);

    request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);
    this.tokenStore.saveAccountInfo(account);
}
 
Example #22
Source File: BearerHeaderAdder.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
@Override
public void onExceptionWithServer(ExecutionContext<HttpClientRequest<ByteBuf>> context, Throwable exception, ExecutionInfo info) {
    KeycloakSecurityContext securityContext = (KeycloakSecurityContext) context.get(KeycloakSecurityContextAssociation.class.getName());
    if (securityContext != null) {
        KeycloakSecurityContextAssociation.associate(securityContext);
    } else {
        KeycloakSecurityContextAssociation.disassociate();
    }
}
 
Example #23
Source File: DrawRessource.java    From keycloak-dropwizard-integration with Apache License 2.0 5 votes vote down vote up
@GET
// @RolesAllowed("user")
public DrawView show() {
    KeycloakSecurityContext session =
            (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    DrawBean bean = new DrawBean();
    DrawView view = new DrawView(bean);
    bean.setIdToken(session.getIdToken());
    return view;
}
 
Example #24
Source File: KeycloakSecurityContextPlaceHolderResolver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> resolve(String placeHolder, HttpFacade httpFacade) {
    String source = placeHolder.substring(placeHolder.indexOf('.') + 1);
    OIDCHttpFacade oidcHttpFacade = OIDCHttpFacade.class.cast(httpFacade);
    KeycloakSecurityContext securityContext = oidcHttpFacade.getSecurityContext();

    if (securityContext == null) {
        return null;
    }

    if (source.endsWith("access_token")) {
        return Arrays.asList(securityContext.getTokenString());
    }

    if (source.endsWith("id_token")) {
        return Arrays.asList(securityContext.getIdTokenString());
    }

    JsonNode jsonNode;

    if (source.startsWith("access_token[")) {
        jsonNode = JsonSerialization.mapper.valueToTree(securityContext.getToken());
    } else if (source.startsWith("id_token[")) {
        jsonNode = JsonSerialization.mapper.valueToTree(securityContext.getIdToken());
    } else {
        throw new RuntimeException("Invalid placeholder [" + placeHolder + "]");
    }

    return JsonUtils.getValues(jsonNode, getParameter(source, "Invalid placeholder [" + placeHolder + "]"));
}
 
Example #25
Source File: JettySessionTokenStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void logout() {
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.removeAttribute(KeycloakSecurityContext.class.getName());
    }
}
 
Example #26
Source File: ElytronSessionTokenStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void logout(boolean glo) {
    HttpScope session = this.httpFacade.getScope(Scope.SESSION);

    if (!session.exists()) {
        return;
    }

    KeycloakSecurityContext ksc = (KeycloakSecurityContext) session.getAttachment(KeycloakSecurityContext.class.getName());

    try {
        if (glo && ksc != null) {
            KeycloakDeployment deployment = httpFacade.getDeployment();

            session.invalidate();

            if (!deployment.isBearerOnly() && ksc != null && ksc instanceof RefreshableKeycloakSecurityContext) {
                ((RefreshableKeycloakSecurityContext) ksc).logout(deployment);
            }
        } else {
            session.setAttachment(ElytronAccount.class.getName(), null);
            session.setAttachment(KeycloakSecurityContext.class.getName(), null);
        }
    } catch (IllegalStateException ise) {
        // Session may be already logged-out in case that app has adminUrl
        log.debugf("Session %s logged-out already", session.getID());
    }
}
 
Example #27
Source File: CatalinaSessionTokenStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void cleanSession(Session catalinaSession) {
    catalinaSession.getSession().removeAttribute(KeycloakSecurityContext.class.getName());
    catalinaSession.getSession().removeAttribute(SerializableKeycloakAccount.class.getName());
    catalinaSession.getSession().removeAttribute(OidcKeycloakAccount.class.getName());
    catalinaSession.setPrincipal(null);
    catalinaSession.setAuthType(null);
}
 
Example #28
Source File: CatalinaSessionTokenStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void checkCurrentToken() {
    Session catalinaSession = request.getSessionInternal(false);
    if (catalinaSession == null) return;
    SerializableKeycloakAccount account = (SerializableKeycloakAccount) catalinaSession.getSession().getAttribute(SerializableKeycloakAccount.class.getName());
    if (account == null) {
        return;
    }

    RefreshableKeycloakSecurityContext session = account.getKeycloakSecurityContext();
    if (session == null) return;

    // just in case session got serialized
    if (session.getDeployment() == null) session.setCurrentRequestInfo(deployment, this);

    if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) {
        request.setAttribute(KeycloakSecurityContext.class.getName(), session);
        request.setUserPrincipal(account.getPrincipal());
        request.setAuthType("KEYCLOAK");
        return;
    }

    // FYI: A refresh requires same scope, so same roles will be set.  Otherwise, refresh will fail and token will
    // not be updated
    boolean success = session.refreshExpiredToken(false);
    if (success && session.isActive()) {
        request.setAttribute(KeycloakSecurityContext.class.getName(), session);
        request.setUserPrincipal(account.getPrincipal());
        request.setAuthType("KEYCLOAK");
        return;
    }

    // Refresh failed, so user is already logged out from keycloak. Cleanup and expire our session
    log.fine("Cleanup and expire session " + catalinaSession.getId() + " after failed refresh");
    request.setUserPrincipal(null);
    request.setAuthType(null);
    cleanSession(catalinaSession);
    catalinaSession.expire();
}
 
Example #29
Source File: KeycloakSecurityContextRequestFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private KeycloakSecurityContext getKeycloakSecurityContext() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication != null) {
        Object principal = authentication.getPrincipal();

        if (principal instanceof KeycloakPrincipal) {
            return KeycloakPrincipal.class.cast(principal).getKeycloakSecurityContext();
        }
    }

    return null;
}
 
Example #30
Source File: ServletRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void propagateKeycloakContext(KeycloakUndertowAccount account) {
    super.propagateKeycloakContext(account);
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
    req.setAttribute(KeycloakSecurityContext.class.getName(), account.getKeycloakSecurityContext());
}