Search in sources :

Example 1 with AccessTokenCredential

use of io.quarkus.oidc.AccessTokenCredential in project quarkus by quarkusio.

the class KeycloakPolicyEnforcerAuthorizer method apply.

@Override
public CheckResult apply(RoutingContext routingContext, SecurityIdentity identity) {
    if (identity.isAnonymous()) {
        PathConfig pathConfig = resolver.getPolicyEnforcer(null).getPathMatcher().matches(routingContext.request().path());
        if (pathConfig != null && pathConfig.getEnforcementMode() == EnforcementMode.ENFORCING) {
            return CheckResult.DENY;
        }
    }
    AccessTokenCredential credential = identity.getCredential(AccessTokenCredential.class);
    if (credential == null) {
        // SecurityIdentity has been created by the authentication mechanism other than quarkus-oidc
        return CheckResult.PERMIT;
    }
    VertxHttpFacade httpFacade = new VertxHttpFacade(routingContext, credential.getToken(), resolver.getReadTimeout());
    KeycloakAdapterPolicyEnforcer adapterPolicyEnforcer = new KeycloakAdapterPolicyEnforcer(resolver.getPolicyEnforcer(identity.getAttribute(TENANT_ID_ATTRIBUTE)));
    AuthorizationContext result = adapterPolicyEnforcer.authorize(httpFacade);
    if (result.isGranted()) {
        SecurityIdentity newIdentity = enhanceSecurityIdentity(identity, result);
        return new CheckResult(true, newIdentity);
    }
    return CheckResult.DENY;
}
Also used : QuarkusSecurityIdentity(io.quarkus.security.runtime.QuarkusSecurityIdentity) SecurityIdentity(io.quarkus.security.identity.SecurityIdentity) PathConfig(org.keycloak.representations.adapters.config.PolicyEnforcerConfig.PathConfig) AuthorizationContext(org.keycloak.AuthorizationContext) AccessTokenCredential(io.quarkus.oidc.AccessTokenCredential) KeycloakAdapterPolicyEnforcer(org.keycloak.adapters.authorization.KeycloakAdapterPolicyEnforcer)

Example 2 with AccessTokenCredential

use of io.quarkus.oidc.AccessTokenCredential in project quarkus by quarkusio.

the class OidcTokenCredentialProducer method currentAccessToken.

@Produces
@RequestScoped
@AlternativePriority(1)
AccessTokenCredential currentAccessToken() {
    AccessTokenCredential cred = identity.getCredential(AccessTokenCredential.class);
    if (cred == null || cred.getToken() == null) {
        LOG.trace("AccessToken is null");
        cred = new AccessTokenCredential();
    }
    return cred;
}
Also used : AccessTokenCredential(io.quarkus.oidc.AccessTokenCredential) AlternativePriority(io.quarkus.arc.AlternativePriority) Produces(javax.enterprise.inject.Produces) RequestScoped(javax.enterprise.context.RequestScoped)

Example 3 with AccessTokenCredential

use of io.quarkus.oidc.AccessTokenCredential in project quarkus by quarkusio.

the class OidcJsonWebTokenProducer method getTokenCredential.

private JsonWebToken getTokenCredential(Class<? extends TokenCredential> type) {
    if (identity.isAnonymous()) {
        return new NullJsonWebToken();
    }
    if (identity.getPrincipal() instanceof OidcJwtCallerPrincipal && ((OidcJwtCallerPrincipal) identity.getPrincipal()).getCredential().getClass() == type) {
        return (JsonWebToken) identity.getPrincipal();
    }
    TokenCredential credential = identity.getCredential(type);
    if (credential != null && credential.getToken() != null) {
        if (credential instanceof AccessTokenCredential && ((AccessTokenCredential) credential).isOpaque()) {
            throw new OIDCException("Opaque access token can not be converted to JsonWebToken");
        }
        JwtClaims jwtClaims;
        try {
            jwtClaims = new JwtConsumerBuilder().setSkipSignatureVerification().setSkipAllValidators().build().processToClaims(credential.getToken());
        } catch (InvalidJwtException e) {
            throw new OIDCException(e);
        }
        jwtClaims.setClaim(Claims.raw_token.name(), credential.getToken());
        return new OidcJwtCallerPrincipal(jwtClaims, credential);
    }
    String tokenType = type == AccessTokenCredential.class ? "access" : "ID";
    LOG.tracef("Current identity is not associated with an %s token", tokenType);
    return new NullJsonWebToken();
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) NullJsonWebToken(io.smallrye.jwt.auth.cdi.NullJsonWebToken) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) OIDCException(io.quarkus.oidc.OIDCException) NullJsonWebToken(io.smallrye.jwt.auth.cdi.NullJsonWebToken) JsonWebToken(org.eclipse.microprofile.jwt.JsonWebToken) AccessTokenCredential(io.quarkus.oidc.AccessTokenCredential) IdTokenCredential(io.quarkus.oidc.IdTokenCredential) TokenCredential(io.quarkus.security.credential.TokenCredential) AccessTokenCredential(io.quarkus.oidc.AccessTokenCredential)

Example 4 with AccessTokenCredential

use of io.quarkus.oidc.AccessTokenCredential in project quarkus by quarkusio.

the class OidcUtils method validateAndCreateIdentity.

static QuarkusSecurityIdentity validateAndCreateIdentity(RoutingContext vertxContext, TokenCredential credential, TenantConfigContext resolvedContext, JsonObject tokenJson, JsonObject rolesJson, UserInfo userInfo, TokenIntrospection introspectionResult) {
    OidcTenantConfig config = resolvedContext.oidcConfig;
    QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder();
    builder.addCredential(credential);
    AuthorizationCodeTokens codeTokens = vertxContext != null ? vertxContext.get(AuthorizationCodeTokens.class.getName()) : null;
    if (codeTokens != null) {
        RefreshToken refreshTokenCredential = new RefreshToken(codeTokens.getRefreshToken());
        builder.addCredential(refreshTokenCredential);
        builder.addCredential(new AccessTokenCredential(codeTokens.getAccessToken(), refreshTokenCredential));
    }
    JsonWebToken jwtPrincipal;
    try {
        JwtClaims jwtClaims = JwtClaims.parse(tokenJson.encode());
        jwtClaims.setClaim(Claims.raw_token.name(), credential.getToken());
        jwtPrincipal = new OidcJwtCallerPrincipal(jwtClaims, credential, config.token.principalClaim.isPresent() ? config.token.principalClaim.get() : null);
    } catch (InvalidJwtException e) {
        throw new AuthenticationFailedException(e);
    }
    builder.addAttribute(QUARKUS_IDENTITY_EXPIRE_TIME, jwtPrincipal.getExpirationTime());
    builder.setPrincipal(jwtPrincipal);
    setRoutingContextAttribute(builder, vertxContext);
    setSecurityIdentityRoles(builder, config, rolesJson);
    setSecurityIdentityUserInfo(builder, userInfo);
    setSecurityIdentityIntrospecton(builder, introspectionResult);
    setSecurityIdentityConfigMetadata(builder, resolvedContext);
    setBlockinApiAttribute(builder, vertxContext);
    setTenantIdAttribute(builder, config);
    return builder.build();
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) RefreshToken(io.quarkus.oidc.RefreshToken) QuarkusSecurityIdentity(io.quarkus.security.runtime.QuarkusSecurityIdentity) JwtClaims(org.jose4j.jwt.JwtClaims) AuthenticationFailedException(io.quarkus.security.AuthenticationFailedException) Builder(io.quarkus.security.runtime.QuarkusSecurityIdentity.Builder) AuthorizationCodeTokens(io.quarkus.oidc.AuthorizationCodeTokens) AccessTokenCredential(io.quarkus.oidc.AccessTokenCredential) JsonWebToken(org.eclipse.microprofile.jwt.JsonWebToken) OidcTenantConfig(io.quarkus.oidc.OidcTenantConfig)

Example 5 with AccessTokenCredential

use of io.quarkus.oidc.AccessTokenCredential in project quarkus by quarkusio.

the class OidcIdentityProvider method createSecurityIdentityWithOidcServer.

private Uni<SecurityIdentity> createSecurityIdentityWithOidcServer(RoutingContext vertxContext, TokenAuthenticationRequest request, TenantConfigContext resolvedContext, final UserInfo userInfo) {
    Uni<TokenVerificationResult> tokenUni = null;
    if (isInternalIdToken(request)) {
        if (vertxContext.get(NEW_AUTHENTICATION) == Boolean.TRUE) {
            // No need to verify it in this case as 'CodeAuthenticationMechanism' has just created it
            tokenUni = Uni.createFrom().item(new TokenVerificationResult(OidcUtils.decodeJwtContent(request.getToken().getToken()), null));
        } else {
            tokenUni = verifySelfSignedTokenUni(resolvedContext, request.getToken().getToken());
        }
    } else {
        tokenUni = verifyTokenUni(resolvedContext, request.getToken().getToken());
    }
    return tokenUni.onItemOrFailure().transformToUni(new BiFunction<TokenVerificationResult, Throwable, Uni<? extends SecurityIdentity>>() {

        @Override
        public Uni<SecurityIdentity> apply(TokenVerificationResult result, Throwable t) {
            if (t != null) {
                return Uni.createFrom().failure(new AuthenticationFailedException(t));
            }
            // Token has been verified, as a JWT or an opaque token, possibly involving
            // an introspection request.
            final TokenCredential tokenCred = request.getToken();
            JsonObject tokenJson = result.localVerificationResult;
            if (tokenJson == null) {
                // JSON token representation may be null not only if it is an opaque access token
                // but also if it is JWT and no JWK with a matching kid is available, asynchronous
                // JWK refresh has not finished yet, but the fallback introspection request has succeeded.
                tokenJson = OidcUtils.decodeJwtContent(tokenCred.getToken());
            }
            if (tokenJson != null) {
                try {
                    OidcUtils.validatePrimaryJwtTokenType(resolvedContext.oidcConfig.token, tokenJson);
                    JsonObject rolesJson = getRolesJson(vertxContext, resolvedContext, tokenCred, tokenJson, userInfo);
                    SecurityIdentity securityIdentity = validateAndCreateIdentity(vertxContext, tokenCred, resolvedContext, tokenJson, rolesJson, userInfo, result.introspectionResult);
                    if (tokenAutoRefreshPrepared(tokenJson, vertxContext, resolvedContext.oidcConfig)) {
                        return Uni.createFrom().failure(new TokenAutoRefreshException(securityIdentity));
                    } else {
                        return Uni.createFrom().item(securityIdentity);
                    }
                } catch (Throwable ex) {
                    return Uni.createFrom().failure(new AuthenticationFailedException(ex));
                }
            } else if (tokenCred instanceof IdTokenCredential || tokenCred instanceof AccessTokenCredential && !((AccessTokenCredential) tokenCred).isOpaque()) {
                return Uni.createFrom().failure(new AuthenticationFailedException("JWT token can not be converted to JSON"));
            } else {
                // Opaque Bearer Access Token
                QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder();
                builder.addCredential(tokenCred);
                OidcUtils.setSecurityIdentityUserInfo(builder, userInfo);
                OidcUtils.setSecurityIdentityIntrospecton(builder, result.introspectionResult);
                OidcUtils.setSecurityIdentityConfigMetadata(builder, resolvedContext);
                String principalMember = "";
                if (result.introspectionResult.contains(OidcConstants.INTROSPECTION_TOKEN_USERNAME)) {
                    principalMember = OidcConstants.INTROSPECTION_TOKEN_USERNAME;
                } else if (result.introspectionResult.contains(OidcConstants.INTROSPECTION_TOKEN_SUB)) {
                    // fallback to "sub", if "username" is not present
                    principalMember = OidcConstants.INTROSPECTION_TOKEN_SUB;
                }
                final String userName = principalMember.isEmpty() ? "" : result.introspectionResult.getString(principalMember);
                builder.setPrincipal(new Principal() {

                    @Override
                    public String getName() {
                        return userName;
                    }
                });
                if (result.introspectionResult.contains(OidcConstants.TOKEN_SCOPE)) {
                    for (String role : result.introspectionResult.getString(OidcConstants.TOKEN_SCOPE).split(" ")) {
                        builder.addRole(role.trim());
                    }
                }
                if (userInfo != null) {
                    OidcUtils.setSecurityIdentityRoles(builder, resolvedContext.oidcConfig, new JsonObject(userInfo.getJsonObject().toString()));
                }
                OidcUtils.setBlockinApiAttribute(builder, vertxContext);
                OidcUtils.setTenantIdAttribute(builder, resolvedContext.oidcConfig);
                OidcUtils.setRoutingContextAttribute(builder, vertxContext);
                return Uni.createFrom().item(builder.build());
            }
        }
    });
}
Also used : QuarkusSecurityIdentity(io.quarkus.security.runtime.QuarkusSecurityIdentity) AuthenticationFailedException(io.quarkus.security.AuthenticationFailedException) JsonObject(io.vertx.core.json.JsonObject) AccessTokenCredential(io.quarkus.oidc.AccessTokenCredential) IdTokenCredential(io.quarkus.oidc.IdTokenCredential) TokenCredential(io.quarkus.security.credential.TokenCredential) QuarkusSecurityIdentity(io.quarkus.security.runtime.QuarkusSecurityIdentity) SecurityIdentity(io.quarkus.security.identity.SecurityIdentity) Uni(io.smallrye.mutiny.Uni) IdTokenCredential(io.quarkus.oidc.IdTokenCredential) AccessTokenCredential(io.quarkus.oidc.AccessTokenCredential) Principal(java.security.Principal)

Aggregations

AccessTokenCredential (io.quarkus.oidc.AccessTokenCredential)7 SecurityIdentity (io.quarkus.security.identity.SecurityIdentity)4 QuarkusSecurityIdentity (io.quarkus.security.runtime.QuarkusSecurityIdentity)4 IdTokenCredential (io.quarkus.oidc.IdTokenCredential)3 AuthenticationFailedException (io.quarkus.security.AuthenticationFailedException)2 TokenCredential (io.quarkus.security.credential.TokenCredential)2 Uni (io.smallrye.mutiny.Uni)2 JsonWebToken (org.eclipse.microprofile.jwt.JsonWebToken)2 JwtClaims (org.jose4j.jwt.JwtClaims)2 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)2 AlternativePriority (io.quarkus.arc.AlternativePriority)1 AuthorizationCodeTokens (io.quarkus.oidc.AuthorizationCodeTokens)1 OIDCException (io.quarkus.oidc.OIDCException)1 OidcTenantConfig (io.quarkus.oidc.OidcTenantConfig)1 RefreshToken (io.quarkus.oidc.RefreshToken)1 AuthenticationRequestContext (io.quarkus.security.identity.AuthenticationRequestContext)1 Builder (io.quarkus.security.runtime.QuarkusSecurityIdentity.Builder)1 QuarkusHttpUser (io.quarkus.vertx.http.runtime.security.QuarkusHttpUser)1 NullJsonWebToken (io.smallrye.jwt.auth.cdi.NullJsonWebToken)1 MultiMap (io.vertx.core.MultiMap)1