Java Code Examples for org.keycloak.KeycloakSecurityContext

The following examples show how to use org.keycloak.KeycloakSecurityContext. These examples are extracted from open source projects. 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 Project: quarkus   Source File: VertxHttpFacade.java    License: 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
@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 3
Source Project: keycloak   Source File: ServletSessionTokenStore.java    License: 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 4
Source Project: hola   Source File: HolaResource.java    License: 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 5
Source Project: thorntail   Source File: SecurityContextServletExtension.java    License: 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 6
Source Project: keycloak   Source File: JettyCookieTokenStore.java    License: 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 7
Source Project: pnc   Source File: KeycloakLoggedInUser.java    License: 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 8
Source Project: keycloak   Source File: SpringSecurityCookieTokenStore.java    License: 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 9
Source Project: keycloak   Source File: JettySessionTokenStore.java    License: 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 10
Source Project: keycloak   Source File: ProductDatabaseClient.java    License: 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 11
Source Project: keycloak   Source File: ElytronCookieTokenStore.java    License: 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 12
@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 13
Source Project: keycloak   Source File: MultiTenantServlet.java    License: 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 14
Source Project: keycloak   Source File: ElytronSessionTokenStore.java    License: 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 15
Source Project: keycloak   Source File: JettySessionTokenStore.java    License: 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 16
Source Project: keycloak   Source File: CatalinaRequestAuthenticator.java    License: 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 17
Source Project: keycloak   Source File: FilterRequestAuthenticator.java    License: 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 18
Source Project: devconf2019-authz   Source File: CarsAppController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/app/show-rpt", method = RequestMethod.GET)
public String showRpt(Principal principal, Model model) throws ServletException, IOException {
    KeycloakSecurityContext securityCtx = AppTokenUtil.getKeycloakSecurityContext(principal);
    AccessToken rptToken = rptStore.getParsedRpt(securityCtx);

    model.addAttribute("token", rptToken);

    String tokenString = mapperProvider.getMapper().writeValueAsString(rptToken);
    model.addAttribute("tokenString", tokenString);

    return "token";
}
 
Example 19
/**
 * Returns the {@link KeycloakSecurityContext} from the Spring {@link ServletRequestAttributes}'s {@link Principal}.
 *
 * The principal must support retrieval of the KeycloakSecurityContext, so at this point, only {@link KeycloakPrincipal}
 * values are supported
 *
 * @return the current <code>KeycloakSecurityContext</code>
 */
protected KeycloakSecurityContext getKeycloakSecurityContext() {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    Principal principal = attributes.getRequest().getUserPrincipal();
    if (principal == null) {
        throw new IllegalStateException("Cannot set authorization header because there is no authenticated principal");
    }
    if (!(principal instanceof KeycloakPrincipal)) {
        throw new IllegalStateException(
                String.format(
                        "Cannot set authorization header because the principal type %s does not provide the KeycloakSecurityContext",
                        principal.getClass()));
    }
    return ((KeycloakPrincipal) principal).getKeycloakSecurityContext();
}
 
Example 20
Source Project: devconf2019-authz   Source File: RptStore.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Can throw HandledException in case that request was successfully submitted through the UMA. We don't need to retry re-sending UMA ticket
 * in this case
 *
 * @param umaTicket
 * @param ctx
 */
public void sendRptRequest(String umaTicket, KeycloakSecurityContext ctx) throws UMAErrorHandler.HandledException {
    RptInfo currentRpt = getCurrentRpt(request, ctx);
    RptInfoResponse rptInfoResponse = sendRptRequest(currentRpt, ctx.getTokenString(), umaTicket);

    // Save as session attribute now
    if (rptInfoResponse.getRptInfo() != null) {
        request.getSession().setAttribute("rpt", rptInfoResponse.getRptInfo());
    } else {
        throw new UMAErrorHandler.HandledException(true);
    }
}
 
Example 21
Source Project: thorntail   Source File: BearerHeaderAdder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onStartWithServer(ExecutionContext<HttpClientRequest<ByteBuf>> context, ExecutionInfo info) throws AbortExecutionException {
    KeycloakSecurityContext securityContext = KeycloakSecurityContextAssociation.get();
    if (securityContext != null) {
        HttpClientRequest<ByteBuf> request = context.getRequest();
        request.withHeader("Authorization", "Bearer " + securityContext.getTokenString());
        context.put(KeycloakSecurityContextAssociation.class.getName(), securityContext);
    } else {
        KeycloakSecurityContextAssociation.disassociate();
    }
}
 
Example 22
Source Project: thorntail   Source File: BearerHeaderAdder.java    License: 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 Project: thorntail   Source File: BearerHeaderAdder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onExecutionFailed(ExecutionContext<HttpClientRequest<ByteBuf>> context, Throwable finalException, ExecutionInfo info) {
    KeycloakSecurityContext securityContext = (KeycloakSecurityContext) context.get(KeycloakSecurityContextAssociation.class.getName());
    if (securityContext != null) {
        KeycloakSecurityContextAssociation.associate(securityContext);
    } else {
        KeycloakSecurityContextAssociation.disassociate();
    }
}
 
Example 24
Source Project: keycloak   Source File: OIDCFilterSessionStore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void saveAccountInfo(OidcKeycloakAccount account) {
    RefreshableKeycloakSecurityContext securityContext = (RefreshableKeycloakSecurityContext) account.getKeycloakSecurityContext();
    Set<String> roles = account.getRoles();

    SerializableKeycloakAccount sAccount = new SerializableKeycloakAccount(roles, account.getPrincipal(), securityContext);
    HttpSession httpSession = request.getSession();
    httpSession.setAttribute(KeycloakAccount.class.getName(), sAccount);
    httpSession.setAttribute(KeycloakSecurityContext.class.getName(), sAccount.getKeycloakSecurityContext());
    if (idMapper != null) idMapper.map(account.getKeycloakSecurityContext().getToken().getSessionState(),  account.getPrincipal().getName(), httpSession.getId());
    //String username = securityContext.getToken().getSubject();
    //log.fine("userSessionManagement.login: " + username);
}
 
Example 25
/**
 * @see io.apicurio.hub.api.security.ILinkedAccountsProvider#initiateLinkedAccount(io.apicurio.hub.core.beans.LinkedAccountType, java.lang.String, java.lang.String)
 */
@Override
public InitiatedLinkedAccount initiateLinkedAccount(LinkedAccountType accountType, String redirectUri,
        String nonce) {
    String authServerRootUrl = config.getKeycloakAuthUrl();
    String realm = config.getKeycloakRealm();
    String provider = accountType.alias();

    KeycloakSecurityContext session = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    AccessToken token = session.getToken();

    String clientId = token.getIssuedFor();
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    String input = nonce + token.getSessionState() + clientId + provider;
    byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
    String hash = Base64Url.encode(check);
    String accountLinkUrl = KeycloakUriBuilder.fromUri(authServerRootUrl)
        .path("/realms/{realm}/broker/{provider}/link").queryParam("nonce", nonce)
        .queryParam("hash", hash).queryParam("client_id", clientId)
        .queryParam("redirect_uri", redirectUri).build(realm, provider).toString();

    logger.debug("Account Link URL: {}", accountLinkUrl);

    // Return the URL that the browser should use to initiate the account linking
    InitiatedLinkedAccount rval = new InitiatedLinkedAccount();
    rval.setAuthUrl(accountLinkUrl);
    rval.setNonce(nonce);
    return rval;
}
 
Example 26
private KeycloakSecurityContext getKeycloakPrincipal() {
    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 27
@Test
public void testCompleteBearerAuthentication() throws Exception {
    authenticator.completeBearerAuthentication(principal, "foo");
    verify(request).setAttribute(eq(KeycloakSecurityContext.class.getName()), eq(refreshableKeycloakSecurityContext));
    assertNotNull(SecurityContextHolder.getContext().getAuthentication());
    assertTrue(KeycloakAuthenticationToken.class.isAssignableFrom(SecurityContextHolder.getContext().getAuthentication().getClass()));
}
 
Example 28
Source Project: keycloak   Source File: SpringSecurityTokenStore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void logout() {

    logger.debug("Handling logout request");
    HttpSession session = request.getSession(false);

    if (session != null) {
        session.setAttribute(KeycloakSecurityContext.class.getName(), null);
        session.invalidate();
    }

    SecurityContextHolder.clearContext();
}
 
Example 29
Source Project: ARCHIVE-wildfly-swarm   Source File: BearerHeaderAdder.java    License: 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 30
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    if (request.getAttribute(FILTER_APPLIED) != null) {
        filterChain.doFilter(request, response);
        return;
    }

    request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

    KeycloakSecurityContext keycloakSecurityContext = getKeycloakSecurityContext();

    if (keycloakSecurityContext instanceof RefreshableKeycloakSecurityContext) {
        RefreshableKeycloakSecurityContext refreshableSecurityContext = (RefreshableKeycloakSecurityContext) keycloakSecurityContext;
        KeycloakDeployment deployment = resolveDeployment(request, response);

        // just in case session got serialized
        if (refreshableSecurityContext.getDeployment()==null) {
            log.trace("Recreating missing deployment and related fields in deserialized context");
            AdapterTokenStore adapterTokenStore = adapterTokenStoreFactory.createAdapterTokenStore(deployment, (HttpServletRequest) request,
                    (HttpServletResponse) response);
            refreshableSecurityContext.setCurrentRequestInfo(deployment, adapterTokenStore);
        }

        if (!refreshableSecurityContext.isActive() || deployment.isAlwaysRefreshToken()) {
            if (refreshableSecurityContext.refreshExpiredToken(false)) {
                request.setAttribute(KeycloakSecurityContext.class.getName(), refreshableSecurityContext);
            } else {
                clearAuthenticationContext();
            }
        }

        request.setAttribute(KeycloakSecurityContext.class.getName(), keycloakSecurityContext);
    }

    filterChain.doFilter(request, response);
}