org.keycloak.adapters.RefreshableKeycloakSecurityContext Java Examples

The following examples show how to use org.keycloak.adapters.RefreshableKeycloakSecurityContext. 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: 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 #2
Source File: KeycloakSpringAdapterUtils.java    From smartling-keycloak-extras with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link RefreshableKeycloakSecurityContext} from the given {@link KeycloakDeployment} and {@link AccessTokenResponse}.
 *
 * @param deployment the <code>KeycloakDeployment</code> for which to create a <code>RefreshableKeycloakSecurityContext</code> (required)
 * @param accessTokenResponse the <code>AccessTokenResponse</code> from which to create a RefreshableKeycloakSecurityContext (required)
 *
 * @return a <code>RefreshableKeycloakSecurityContext</code> created from the given <code>accessTokenResponse</code>
 * @throws VerificationException if the given <code>AccessTokenResponse</code> contains an invalid {@link IDToken}
 */
public static RefreshableKeycloakSecurityContext createKeycloakSecurityContext(KeycloakDeployment deployment, AccessTokenResponse accessTokenResponse) throws VerificationException {
    String tokenString = accessTokenResponse.getToken();
    String idTokenString = accessTokenResponse.getIdToken();
    AccessToken accessToken = RSATokenVerifier
            .verifyToken(tokenString, deployment.getRealmKey(), deployment.getRealmInfoUrl());
    IDToken idToken;

    try {
        JWSInput input = new JWSInput(idTokenString);
        idToken = input.readJsonContent(IDToken.class);
    } catch (JWSInputException e) {
        throw new VerificationException("Unable to verify ID token", e);
    }

    // FIXME: does it make sense to pass null for the token store?
    return new RefreshableKeycloakSecurityContext(deployment, null, tokenString, accessToken, idTokenString, idToken, accessTokenResponse.getRefreshToken());
}
 
Example #3
Source File: KeycloakDirectAccessGrantService.java    From smartling-keycloak-extras with Apache License 2.0 6 votes vote down vote up
@Override
public RefreshableKeycloakSecurityContext login(String username, String password) throws VerificationException {

    final MultiValueMap<String,String> body = new LinkedMultiValueMap<>();
    final HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    body.set("username", username);
    body.set("password", password);
    body.set(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);

    AccessTokenResponse response = template.postForObject(keycloakDeployment.getTokenUrl(), new HttpEntity<>(body, headers), AccessTokenResponse.class);

    return KeycloakSpringAdapterUtils.createKeycloakSecurityContext(keycloakDeployment, response);
}
 
Example #4
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 #5
Source File: JettyCookieTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Verify if we already have authenticated and active principal in cookie. Perform refresh if it's not active
 *
 * @return valid principal
 */
protected KeycloakPrincipal<RefreshableKeycloakSecurityContext> checkPrincipalFromCookie() {
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = CookieTokenStore.getPrincipalFromCookie(deployment, facade, this);
    if (principal == null) {
        log.debug("Account was not in cookie or was invalid");
        return null;
    }

    RefreshableKeycloakSecurityContext session = principal.getKeycloakSecurityContext();

    if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) return principal;
    boolean success = session.refreshExpiredToken(false);
    if (success && session.isActive()) return principal;

    log.debugf("Cleanup and expire cookie for user %s after failed refresh", principal.getName());
    CookieTokenStore.removeCookie(deployment, facade);
    return null;
}
 
Example #6
Source File: AbstractKeycloakLoginModule.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Called after accessToken was verified (including signature, expiration etc)
 *
 */
protected Auth postTokenVerification(String tokenString, AccessToken token) {
    boolean verifyCaller;
    if (deployment.isUseResourceRoleMappings()) {
        verifyCaller = token.isVerifyCaller(deployment.getResourceName());
    } else {
        verifyCaller = token.isVerifyCaller();
    }
    if (verifyCaller) {
        throw new IllegalStateException("VerifyCaller not supported yet in login module");
    }

    RefreshableKeycloakSecurityContext skSession = new RefreshableKeycloakSecurityContext(deployment, null, tokenString, token, null, null, null);
    String principalName = AdapterUtils.getPrincipalName(deployment, token);
    final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(principalName, skSession);
    final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(skSession);
    return new Auth(principal, roles, tokenString);
}
 
Example #7
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 #8
Source File: ElytronCookieTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void checkCurrentToken() {
    KeycloakDeployment deployment = httpFacade.getDeployment();
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = CookieTokenStore.getPrincipalFromCookie(deployment, httpFacade, this);

    if (principal == null) {
        return;
    }

    RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext();

    if (securityContext.isActive() && !securityContext.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 = securityContext.refreshExpiredToken(false);
    if (success && securityContext.isActive()) return;

    saveAccountInfo(new ElytronAccount(principal));
}
 
Example #9
Source File: KeycloakRouteZuulFilter.java    From spring-cloud-yes with Apache License 2.0 6 votes vote down vote up
private void addKeycloakTokenToHeader(RequestContext ctx) {
    Principal principal = ctx.getRequest()
            .getUserPrincipal();

    // 这里之所以可以直接强制转换,是因为shouldFilter中已经做了类型判断。
    KeycloakSecurityContext keycloakSecurityContext = ((KeycloakPrincipal) principal)
            .getKeycloakSecurityContext();

    if (keycloakSecurityContext instanceof RefreshableKeycloakSecurityContext) {
        ctx.addZuulRequestHeader(AUTHORIZATION_HEADER,
                this.buildBearerToken(
                        (RefreshableKeycloakSecurityContext) keycloakSecurityContext
                )
        );
    }
    // 用户没有登录,啥都不干
}
 
Example #10
Source File: CatalinaCookieTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Verify if we already have authenticated and active principal in cookie. Perform refresh if it's not active
 *
 * @return valid principal
 */
protected KeycloakPrincipal<RefreshableKeycloakSecurityContext> checkPrincipalFromCookie() {
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = CookieTokenStore.getPrincipalFromCookie(deployment, facade, this);
    if (principal == null) {
        log.fine("Account was not in cookie or was invalid");
        return null;
    }

    RefreshableKeycloakSecurityContext session = principal.getKeycloakSecurityContext();

    if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) return principal;
    boolean success = session.refreshExpiredToken(false);
    if (success && session.isActive()) return principal;

    log.fine("Cleanup and expire cookie for user " + principal.getName() + " after failed refresh");
    request.setUserPrincipal(null);
    request.setAuthType(null);
    CookieTokenStore.removeCookie(deployment, facade);
    return null;
}
 
Example #11
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 #12
Source File: SpringSecurityCookieTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Verify if we already have authenticated and active principal in cookie. Perform refresh if
 * it's not active
 *
 * @return valid principal
 */
private KeycloakPrincipal<RefreshableKeycloakSecurityContext> checkPrincipalFromCookie() {
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal =
            CookieTokenStore.getPrincipalFromCookie(deployment, facade, this);
    if (principal == null) {
        logger.debug("Account was not in cookie or was invalid");
        return null;
    }

    RefreshableKeycloakSecurityContext session = principal.getKeycloakSecurityContext();

    if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) return principal;
    boolean success = session.refreshExpiredToken(false);
    if (success && session.isActive()) {
        refreshCallback(session);
        return principal;
    }

    logger.debug(
            "Cleanup and expire cookie for user {} after failed refresh", principal.getName());
    CookieTokenStore.removeCookie(deployment, facade);
    return null;
}
 
Example #13
Source File: KeycloakAuthenticatedActionsFilter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@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 = getKeycloakPrincipal();

    if (keycloakSecurityContext instanceof RefreshableKeycloakSecurityContext) {
        HttpFacade facade = new SimpleHttpFacade((HttpServletRequest) request, (HttpServletResponse) response);
        KeycloakDeployment deployment = resolveDeployment(request, response);
        AuthenticatedActionsHandler actions = new AuthenticatedActionsHandler(deployment, OIDCHttpFacade.class.cast(facade));
        if (actions.handledRequest()) {
            return;
        }
    }

    filterChain.doFilter(request, response);
}
 
Example #14
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 #15
Source File: KeycloakUndertowAccount.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public boolean checkActive() {
    // this object may have been serialized, so we need to reset realm config/metadata
    RefreshableKeycloakSecurityContext session = getKeycloakSecurityContext();
    if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) {
        log.debug("session is active");
        return true;
    }

    log.debug("session is not active or refresh is enforced. Try refresh");
    boolean success = session.refreshExpiredToken(false);
    if (!success || !session.isActive()) {
        log.debug("session is not active return with failure");

        return false;
    }
    log.debug("refresh succeeded");

    setRoles(session);
    return true;
}
 
Example #16
Source File: CatalinaCookieTokenStore.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.fine("remote logged in already. Establish state from cookie");
        RefreshableKeycloakSecurityContext securityContext = authenticatedPrincipal.getKeycloakSecurityContext();

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

        securityContext.setCurrentRequestInfo(deployment, this);
        Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
        GenericPrincipal principal = principalFactory.createPrincipal(request.getContext().getRealm(), authenticatedPrincipal, roles);

        request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);
        request.setUserPrincipal(principal);
        request.setAuthType("KEYCLOAK");
        return true;
    } else {
        return false;
    }
}
 
Example #17
Source File: UndertowCookieTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isCached(RequestAuthenticator authenticator) {
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = CookieTokenStore.getPrincipalFromCookie(deployment, facade, this);
    if (principal == null) {
        log.debug("Account was not in cookie or was invalid, returning null");
        return false;
    }
    KeycloakUndertowAccount account = new KeycloakUndertowAccount(principal);

    if (!deployment.getRealm().equals(account.getKeycloakSecurityContext().getRealm())) {
        log.debug("Account in session belongs to a different realm than for this request.");
        return false;
    }

    if (account.checkActive()) {
        log.debug("Cached account found");
        securityContext.authenticationComplete(account, "KEYCLOAK", false);
        ((AbstractUndertowRequestAuthenticator)authenticator).propagateKeycloakContext(account);
        return true;
    } else {
        log.debug("Account was not active, removing cookie and returning false");
        CookieTokenStore.removeCookie(deployment, facade);
        return false;
    }
}
 
Example #18
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 #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: ElytronCookieTokenStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isCached(RequestAuthenticator authenticator) {
    KeycloakDeployment deployment = httpFacade.getDeployment();
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = CookieTokenStore.getPrincipalFromCookie(deployment, httpFacade, this);
    if (principal == null) {
        log.debug("Account was not in cookie or was invalid, returning null");
        return false;
    }
    ElytronAccount account = new ElytronAccount(principal);

    if (!deployment.getRealm().equals(account.getKeycloakSecurityContext().getRealm())) {
        log.debug("Account in session belongs to a different realm than for this request.");
        return false;
    }

    boolean active = account.checkActive();

    if (!active) {
        active = account.tryRefresh();
    }

    if (active) {
        log.debug("Cached account found");
        restoreRequest();
        httpFacade.authenticationComplete(account, true);
        return true;
    } else {
        log.debug("Account was not active, removing cookie and returning false");
        CookieTokenStore.removeCookie(deployment, httpFacade);
        return false;
    }
}
 
Example #21
Source File: ElytronAccount.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public boolean checkActive() {
    RefreshableKeycloakSecurityContext session = getKeycloakSecurityContext();

    if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) {
        log.debug("session is active");
        return true;
    }

    log.debug("session not active");

    return false;
}
 
Example #22
Source File: KeycloakSecurityContextRequestFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #23
Source File: OlaController.java    From ola with Apache License 2.0 5 votes vote down vote up
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, value = "/ola-secured", produces = "text/plain")
@ApiOperation("Returns a message that is only available for authenticated users")
public String olaSecured(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
    AccessToken token = principal.getKeycloakSecurityContext().getToken();
    return "This is a Secured resource. You are logged as " + token.getName();
}
 
Example #24
Source File: KeycloakLogoutHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void handleSingleSignOut(HttpServletRequest request, HttpServletResponse response, KeycloakAuthenticationToken authenticationToken) {
    HttpFacade facade = new SimpleHttpFacade(request, response);
    KeycloakDeployment deployment = adapterDeploymentContext.resolveDeployment(facade);
    adapterTokenStoreFactory.createAdapterTokenStore(deployment, request, response).logout();
    RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) authenticationToken.getAccount().getKeycloakSecurityContext();
    session.logout(deployment);
}
 
Example #25
Source File: UserDetailsArgumentResolver.java    From slackspace-angular-spring-keycloak with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Object createUserDetails(NativeWebRequest webRequest) {
	KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal =
			(KeycloakPrincipal<RefreshableKeycloakSecurityContext>) webRequest.getUserPrincipal();

	AccessToken token = principal.getKeycloakSecurityContext().getToken();

	return new UserDetails(token.getId(), token.getGivenName(), token.getFamilyName(), token.getEmail(),
			token.getRealmAccess().getRoles());
}
 
Example #26
Source File: CatalinaRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void completeBearerAuthentication(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal, String method) {
    RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext();
    Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
    if (log.isLoggable(Level.FINE)) {
        log.fine("Completing bearer authentication. Bearer roles: " + roles);
    }
    Principal generalPrincipal = principalFactory.createPrincipal(request.getContext().getRealm(), principal, roles);
    request.setUserPrincipal(generalPrincipal);
    request.setAuthType(method);
    request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);
}
 
Example #27
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 #28
Source File: ElytronHttpFacade.java    From keycloak with Apache License 2.0 5 votes vote down vote up
void authenticationComplete() {
    if (securityIdentity != null) {
        HttpScope requestScope = request.getScope(Scope.EXCHANGE);
        RefreshableKeycloakSecurityContext keycloakSecurityContext = account.getKeycloakSecurityContext();

        requestScope.setAttachment(KeycloakSecurityContext.class.getName(), keycloakSecurityContext);

        this.request.authenticationComplete(response -> {
            if (!restored) {
                responseConsumer.accept(response);
            }
        }, () -> ((ElytronTokeStore) tokenStore).logout(true));
    }
}
 
Example #29
Source File: KeycloakDirectAccessGrantAuthenticationProvider.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
protected Authentication postTokenVerification(String tokenString, AccessToken token) {
    RefreshableKeycloakSecurityContext skSession = new RefreshableKeycloakSecurityContext(deployment, null, tokenString, token, null, null, null);
    String principalName = AdapterUtils.getPrincipalName(deployment, token);
    final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(principalName, skSession);
    final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(skSession);
    final KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, skSession);
    KeycloakAuthenticationToken newAuth = new KeycloakAuthenticationToken(account, false);
    //call to the super logic to map authorities
    return super.authenticate(newAuth);
}
 
Example #30
Source File: SpringSecurityRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void completeBearerAuthentication(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal, String method) {

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

    logger.debug("Completing bearer authentication. Bearer roles: {} ",roles);

    SecurityContext context = SecurityContextHolder.createEmptyContext();
    context.setAuthentication(new KeycloakAuthenticationToken(account, false));
    SecurityContextHolder.setContext(context);

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