Java源码示例:org.keycloak.adapters.AdapterUtils

示例1
@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);
}
 
示例2
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;
}
 
示例3
/**
 * 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);
}
 
示例4
@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);
}
 
示例5
@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;
    }
}
 
示例6
@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;
}
 
示例7
@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;
}
 
示例8
@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;
    }
}
 
示例9
@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);
}
 
示例10
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);
}
 
示例11
/**
 * 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);
}
 
示例12
@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);
}
 
示例13
@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;
}
 
示例14
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;
}
 
示例15
@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);
}
 
示例16
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);
}
 
示例17
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;
}
 
示例18
@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);
}
 
示例19
@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);
}
 
示例20
@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);
}
 
示例21
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);
}
 
示例22
@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);
}
 
示例23
protected void setRoles(RefreshableKeycloakSecurityContext session) {
    Set<String> roles = AdapterUtils.getRolesFromSecurityContext(session);
    this.accountRoles = roles;
}
 
示例24
@Override
public void refreshCallback(RefreshableKeycloakSecurityContext securityContext) {
    KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(AdapterUtils.getPrincipalName(this.httpFacade.getDeployment(), securityContext.getToken()), securityContext);
    saveAccountInfo(new ElytronAccount(principal));
}
 
示例25
/**
 * 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);
}