org.keycloak.KeycloakPrincipal Java Examples

The following examples show how to use org.keycloak.KeycloakPrincipal. 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: ProtectedServlet.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().contains("logout")) {
        req.logout();
        resp.sendRedirect(req.getContextPath() + "/" + realm);
        return;
    }

    KeycloakPrincipal principal = (KeycloakPrincipal) req.getUserPrincipal();

    resp.setContentType("text/html");
    PrintWriter writer = resp.getWriter();

    writer.write("Realm: ");
    writer.write(principal.getKeycloakSecurityContext().getRealm());

    writer.write("<br/>User: ");
    writer.write(principal.getKeycloakSecurityContext().getIdToken().getPreferredUsername());

    writer.write(String.format("<br/><a href=\"/multitenant/%s/logout\">Logout</a>", realm));
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
Source File: ArticleController.java    From spring-cloud-yes with Apache License 2.0 6 votes vote down vote up
@GetMapping("")
public PageInfo<Article> search(
        Principal principal,
        @RequestParam(required = false) String keyword,
        PageVoWithSort4Mybatis pageVo
) {
    if (principal instanceof KeycloakPrincipal) {
        AccessToken accessToken = ((KeycloakPrincipal) principal).getKeycloakSecurityContext().getToken();
        String preferredUsername = accessToken.getPreferredUsername();
        AccessToken.Access realmAccess = accessToken.getRealmAccess();
        Set<String> roles = realmAccess.getRoles();
        log.info("当前登录用户:{}, 角色:{}", preferredUsername, roles);
    }

    PageHelper.startPage(pageVo.getPage(), pageVo.getRows(), pageVo.getSort());

    if (StringUtils.isEmpty(keyword)) {
        return new PageInfo<>(
                this.articleMapper.selectAll()
        );
    }

    return new PageInfo<>(
            this.articleMapper.searchByCondition(keyword)
    );
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
Source File: GSSCredentialsClient.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static LDAPUser getUserFromLDAP(HttpServletRequest req) throws Exception {
    KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) req.getUserPrincipal();
    AccessToken accessToken = keycloakPrincipal.getKeycloakSecurityContext().getToken();
    String username = accessToken.getPreferredUsername();

    // Retrieve kerberos credential from accessToken and deserialize it
    String serializedGssCredential = (String) accessToken.getOtherClaims().get(KerberosConstants.GSS_DELEGATION_CREDENTIAL);
    GSSCredential deserializedGssCredential = KerberosSerializationUtils.deserializeCredential(serializedGssCredential);

    // First try to invoke without gssCredential. It should fail. This is here just for illustration purposes
    try {
        invokeLdap(null, username);
        throw new RuntimeException("Not expected to authenticate to LDAP without credential");
    } catch (NamingException nse) {
        System.out.println("GSSCredentialsClient: Expected exception: " + nse.getMessage());
    }

    return invokeLdap(deserializedGssCredential, username);
}
 
Example #12
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 #13
Source File: ProtectedServlet.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().contains("logout")) {
        req.logout();
        resp.sendRedirect(req.getContextPath() + "/" + realm);
        return;
    }

    KeycloakPrincipal principal = (KeycloakPrincipal) req.getUserPrincipal();

    resp.setContentType("text/html");
    PrintWriter writer = resp.getWriter();

    writer.write("Realm: ");
    writer.write(principal.getKeycloakSecurityContext().getRealm());

    writer.write("<br/>User: ");
    writer.write(principal.getKeycloakSecurityContext().getIdToken().getPreferredUsername());

    writer.write(String.format("<br/><a href=\"/multitenant/%s/logout\">Logout</a>", realm));
}
 
Example #14
Source File: LoginModulesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testDirectAccessGrantLoginModuleLoginSuccess() throws Exception {
    oauth.realm("demo");

    LoginContext loginContext = directGrantLogin(null);
    Subject subject = loginContext.getSubject();

    // Assert principals in subject
    KeycloakPrincipal principal = subject.getPrincipals(KeycloakPrincipal.class).iterator().next();
    Assert.assertEquals("[email protected]", principal.getKeycloakSecurityContext().getToken().getPreferredUsername());
    assertToken(principal.getKeycloakSecurityContext().getTokenString(), true);

    Set<RolePrincipal> roles = subject.getPrincipals(RolePrincipal.class);
    Assert.assertEquals(1, roles.size());
    Assert.assertEquals("user", roles.iterator().next().getName());

    // Logout and assert token not valid anymore
    loginContext.logout();
    assertToken(principal.getKeycloakSecurityContext().getTokenString(), false);
}
 
Example #15
Source File: LoginModulesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testBearerLoginFailedLogin() throws Exception {
    oauth.realm("demo");

    LoginContext directGrantCtx = directGrantLogin(null);
    String accessToken = directGrantCtx.getSubject().getPrincipals(KeycloakPrincipal.class).iterator().next()
            .getKeycloakSecurityContext().getTokenString();

    LoginContext bearerCtx = new LoginContext("does-not-matter", null,
            createJaasCallbackHandler("doesn-not-matter", accessToken),
            createJaasConfigurationForBearer());

    // Login should fail due insufficient audience in the token
    try {
        bearerCtx.login();
        Assert.fail("Not expected to successfully login");
    } catch (LoginException le) {
        // Ignore
    }

    directGrantCtx.logout();
}
 
Example #16
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 #17
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 #18
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 #19
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 #20
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 #21
Source File: JettyRequestAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void completeOAuthAuthentication(final KeycloakPrincipal<RefreshableKeycloakSecurityContext> skp) {
    principal = 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 #22
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 #23
Source File: AbstractKeycloakLoginModule.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean logout() throws LoginException {
    Set<Principal> principals = new HashSet<Principal>(subject.getPrincipals());
    for (Principal principal : principals) {
        if (principal.getClass().equals(KeycloakPrincipal.class) || principal.getClass().equals(RolePrincipal.class)) {
            subject.getPrincipals().remove(principal);
        }
    }
    Set<Object> creds = subject.getPrivateCredentials();
    for (Object cred : creds) {
        subject.getPrivateCredentials().remove(cred);
    }
    subject = null;
    callbackHandler = null;
    return true;
}
 
Example #24
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 #25
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 #26
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 #27
Source File: AbstractKeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected Authentication register(Request request, KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
    request.setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext);
    Authentication authentication = request.getAuthentication();
    if (!(authentication instanceof KeycloakAuthentication)) {
        UserIdentity userIdentity = createIdentity(principal);
        authentication = createAuthentication(userIdentity, request);
        request.setAuthentication(authentication);
    }
    return authentication;
}
 
Example #28
Source File: UndertowCookieTokenStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void logout() {
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = CookieTokenStore.getPrincipalFromCookie(deployment, facade, this);
    if (principal == null) return;

    CookieTokenStore.removeCookie(deployment, facade);
}
 
Example #29
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);
}
 
Example #30
Source File: AbstractUndertowRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void completeOAuthAuthentication(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
    KeycloakUndertowAccount account = createAccount(principal);
    securityContext.authenticationComplete(account, "KEYCLOAK", false);
    propagateKeycloakContext(account);
    tokenStore.saveAccountInfo(account);
}