org.keycloak.adapters.AdapterUtils Java Examples

The following examples show how to use org.keycloak.adapters.AdapterUtils. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: JWTClientSecretCredentialsProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private JsonWebToken createRequestToken(String clientId, String realmInfoUrl) {
    // According to <a href="http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication">OIDC's client authentication spec</a>,
    // JWT claims is the same as one by private_key_jwt

    JsonWebToken reqToken = new JsonWebToken();
    reqToken.id(AdapterUtils.generateId());
    reqToken.issuer(clientId);
    reqToken.subject(clientId);
    reqToken.audience(realmInfoUrl);

    int now = Time.currentTime();
    reqToken.issuedAt(now);
    // the same as in KEYCLOAK-2986, JWTClientCredentialsProvider's timeout field
    reqToken.expiration(now + 10);
    reqToken.notBefore(now);
    return reqToken;
}
 
Example #9
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 #10
Source File: JaxrsBearerTokenFilterImpl.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void propagateSecurityContext(JaxrsHttpFacade facade, ContainerRequestContext request, KeycloakDeployment resolvedDeployment, BearerTokenRequestAuthenticator bearer) {
    RefreshableKeycloakSecurityContext skSession = new RefreshableKeycloakSecurityContext(resolvedDeployment, null, bearer.getTokenString(), bearer.getToken(), null, null, null);

    // Not needed to do resteasy specifics as KeycloakSecurityContext can be always retrieved from SecurityContext by typecast SecurityContext.getUserPrincipal to KeycloakPrincipal
    // ResteasyProviderFactory.pushContext(KeycloakSecurityContext.class, skSession);

    facade.setSecurityContext(skSession);
    String principalName = AdapterUtils.getPrincipalName(resolvedDeployment, bearer.getToken());
    final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(principalName, skSession);
    SecurityContext anonymousSecurityContext = getRequestSecurityContext(request);
    final boolean isSecure = anonymousSecurityContext.isSecure();
    final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(skSession);

    SecurityContext ctx = new SecurityContext() {
        @Override
        public Principal getUserPrincipal() {
            return principal;
        }

        @Override
        public boolean isUserInRole(String role) {
            return roles.contains(role);
        }

        @Override
        public boolean isSecure() {
            return isSecure;
        }

        @Override
        public String getAuthenticationScheme() {
            return "OAUTH_BEARER";
        }
    };
    request.setSecurityContext(ctx);
}
 
Example #11
Source File: JWTClientCredentialsProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected JsonWebToken createRequestToken(String clientId, String realmInfoUrl) {
    JsonWebToken reqToken = new JsonWebToken();
    reqToken.id(AdapterUtils.generateId());
    reqToken.issuer(clientId);
    reqToken.subject(clientId);
    reqToken.audience(realmInfoUrl);

    int now = Time.currentTime();
    reqToken.issuedAt(now);
    reqToken.expiration(now + this.tokenTimeout);
    reqToken.notBefore(now);

    return reqToken;
}
 
Example #12
Source File: FilterRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void completeBearerAuthentication(final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal, String method) {
    final RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext();
    final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
    if (log.isLoggable(Level.FINE)) {
        log.fine("Completing bearer authentication. Bearer roles: " + roles);
    }
    request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);
    OidcKeycloakAccount account = new OidcKeycloakAccount() {

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

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

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

    };
    // need this here to obtain UserPrincipal
    request.setAttribute(KeycloakAccount.class.getName(), account);
}
 
Example #13
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 #14
Source File: ClientAuthSignedJWTTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private JsonWebToken createRequestToken(String clientId, String realmInfoUrl) {
    JsonWebToken reqToken = new JsonWebToken();
    reqToken.id(AdapterUtils.generateId());
    reqToken.issuer(clientId);
    reqToken.subject(clientId);
    reqToken.audience(realmInfoUrl);

    int now = Time.currentTime();
    reqToken.issuedAt(now);
    reqToken.expiration(now + 10);
    reqToken.notBefore(now);

    return reqToken;
}
 
Example #15
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 #16
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 #17
Source File: ClientAuthSignedJWTTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected JsonWebToken createRequestToken(String clientId, String realmInfoUrl) {
    JsonWebToken reqToken = new JsonWebToken();
    if (isClaimEnabled("id")) reqToken.id(AdapterUtils.generateId());
    if (isClaimEnabled("issuer")) reqToken.issuer(clientId);
    if (isClaimEnabled("subject")) reqToken.subject(clientId);
    if (isClaimEnabled("audience")) reqToken.audience(realmInfoUrl);

    int now = Time.currentTime();
    if (isClaimEnabled("issuedAt")) reqToken.issuedAt(now);
    if (isClaimEnabled("expiration")) reqToken.expiration(now + getTokenTimeout());
    if (isClaimEnabled("notBefore")) reqToken.notBefore(now);

    return reqToken;
}
 
Example #18
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 #19
Source File: AbstractKeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static UserIdentity createIdentity(KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
    Set<String> roles = AdapterUtils.getRolesFromSecurityContext(principal.getKeycloakSecurityContext());
    if (roles == null) {
        roles = new HashSet<String>();
    }
    Subject theSubject = new Subject();
    String[] theRoles = new String[roles.size()];
    roles.toArray(theRoles);

    return new DefaultUserIdentity(theSubject, principal, theRoles);
}
 
Example #20
Source File: KeycloakSpringAdapterUtilsTest.java    From smartling-keycloak-extras with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    MockitoAnnotations.initMocks(this);
    SimpleAuthorityMapper roleMapper = new SimpleAuthorityMapper();
    roleMapper.setConvertToUpperCase(true);
    grantedAuthoritiesMapper = roleMapper;

    PowerMockito.mockStatic(AdapterUtils.class);
    when(AdapterUtils.getRolesFromSecurityContext(any(RefreshableKeycloakSecurityContext.class))).thenReturn(AUTHORITIES);
    when(AdapterUtils.createPrincipal(eq(deployment), eq(context))).thenReturn(principal);
}
 
Example #21
Source File: KeycloakSpringAdapterUtils.java    From smartling-keycloak-extras with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link GrantedAuthority} collection from the given {@link KeycloakSecurityContext}.
 *
 * @param context the current <code>RefreshableKeycloakSecurityContext</code> (required)
 * @param mapper an optional {@link GrantedAuthoritiesMapper} to convert the
 * authorities loaded the given <code>context</code> which will be used in the
 * {@code Authentication} object
 *
 * @return a {@link GrantedAuthority} collection if any; an empty list otherwise
 */
public static Collection<? extends GrantedAuthority> createGrantedAuthorities(RefreshableKeycloakSecurityContext context, GrantedAuthoritiesMapper mapper) {
    Assert.notNull(context, "RefreshableKeycloakSecurityContext cannot be null");
    List<KeycloakRole> grantedAuthorities = new ArrayList<>();

    for (String role : AdapterUtils.getRolesFromSecurityContext(context)) {
        grantedAuthorities.add(new KeycloakRole(role));
    }

    return mapper != null ? mapper.mapAuthorities(grantedAuthorities) : Collections.unmodifiableList(grantedAuthorities);
}
 
Example #22
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 #23
Source File: ElytronSessionTokenStore.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void refreshCallback(RefreshableKeycloakSecurityContext securityContext) {
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(AdapterUtils.getPrincipalName(this.httpFacade.getDeployment(), securityContext.getToken()), securityContext);
    saveAccountInfo(new ElytronAccount(principal));
}
 
Example #24
Source File: KeycloakUndertowAccount.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void setRoles(RefreshableKeycloakSecurityContext session) {
    Set<String> roles = AdapterUtils.getRolesFromSecurityContext(session);
    this.accountRoles = roles;
}
 
Example #25
Source File: KeycloakSpringAdapterUtils.java    From smartling-keycloak-extras with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a {@link OidcKeycloakAccount} from the given {@link KeycloakDeployment} and {@link RefreshableKeycloakSecurityContext}.
 *
 * @param deployment the <code>KeycloakDeployment</code> requesting an account (required)
 * @param context the current <code>RefreshableKeycloakSecurityContext</code> (required)
 *
 * @return a <code>KeycloakAccount</code> for the given <code>deployment</code> and <code>context</code>
 */
public static OidcKeycloakAccount createAccount(KeycloakDeployment deployment, RefreshableKeycloakSecurityContext context) {
    Assert.notNull(context);
    Set<String> roles = AdapterUtils.getRolesFromSecurityContext(context);
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = AdapterUtils.createPrincipal(deployment, context);
    return new SimpleKeycloakAccount(principal, roles, context);
}