Search in sources :

Example 11 with OauthClientConfiguration

use of io.micronaut.security.oauth2.configuration.OauthClientConfiguration in project micronaut-security by micronaut-projects.

the class OpenIdClientCondition method matches.

@Override
public boolean matches(ConditionContext context) {
    AnnotationMetadataProvider component = context.getComponent();
    BeanContext beanContext = context.getBeanContext();
    if (beanContext instanceof ApplicationContext && component instanceof ValueResolver) {
        Optional<String> optional = ((ValueResolver) component).get(Named.class.getName(), String.class);
        if (optional.isPresent()) {
            String name = optional.get();
            OauthClientConfiguration clientConfiguration = beanContext.getBean(OauthClientConfiguration.class, Qualifiers.byName(name));
            OpenIdClientConfiguration openIdClientConfiguration = clientConfiguration.getOpenid().get();
            String failureMessagePrefix = "Skipped OpenID client creation for provider [" + name;
            if (clientConfiguration.isEnabled()) {
                if (openIdClientConfiguration.getIssuer().isPresent() || endpointsManuallyConfigured(openIdClientConfiguration)) {
                    if (clientConfiguration.getGrantType() == GrantType.AUTHORIZATION_CODE) {
                        Optional<AuthorizationEndpointConfiguration> authorization = openIdClientConfiguration.getAuthorization();
                        if (!authorization.isPresent() || authorization.get().getResponseType() == ResponseType.CODE) {
                            return true;
                        } else {
                            context.fail(failureMessagePrefix + "] because the response type is not 'code'");
                        }
                    } else {
                        context.fail(failureMessagePrefix + "] because the grant type is not 'authorization-code'");
                    }
                } else {
                    context.fail(failureMessagePrefix + "] because no issuer is configured");
                }
            } else {
                context.fail(failureMessagePrefix + "] because the configuration is disabled");
            }
            return false;
        }
    }
    return true;
}
Also used : BeanContext(io.micronaut.context.BeanContext) Named(io.micronaut.core.naming.Named) AuthorizationEndpointConfiguration(io.micronaut.security.oauth2.configuration.endpoints.AuthorizationEndpointConfiguration) ApplicationContext(io.micronaut.context.ApplicationContext) ValueResolver(io.micronaut.core.value.ValueResolver) AnnotationMetadataProvider(io.micronaut.core.annotation.AnnotationMetadataProvider) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration) OpenIdClientConfiguration(io.micronaut.security.oauth2.configuration.OpenIdClientConfiguration)

Example 12 with OauthClientConfiguration

use of io.micronaut.security.oauth2.configuration.OauthClientConfiguration in project micronaut-security by micronaut-projects.

the class OpenIdClientFactory method openIdClient.

/**
 * Creates an {@link OpenIdClient} from the provided parameters.
 *
 * @param openIdClientConfiguration The openid client configuration
 * @param clientConfiguration The client configuration
 * @param openIdProviderMetadata The open id provider metadata
 * @param authenticationMapper The user details mapper
 * @param redirectUrlBuilder The redirect URL builder
 * @param authorizationResponseHandler The authorization response handler
 * @param endSessionEndpointResolver The end session resolver
 * @param endSessionCallbackUrlBuilder The end session callback URL builder
 * @return The OpenID client, or null if the client configuration does not allow it
 */
@EachBean(OpenIdClientConfiguration.class)
@Requires(condition = OpenIdClientCondition.class)
@SuppressWarnings("java:S107")
DefaultOpenIdClient openIdClient(@Parameter OpenIdClientConfiguration openIdClientConfiguration, @Parameter OauthClientConfiguration clientConfiguration, @Parameter BeanProvider<DefaultOpenIdProviderMetadata> openIdProviderMetadata, @Parameter @Nullable OpenIdAuthenticationMapper authenticationMapper, AuthorizationRedirectHandler redirectUrlBuilder, OpenIdAuthorizationResponseHandler authorizationResponseHandler, EndSessionEndpointResolver endSessionEndpointResolver, EndSessionCallbackUrlBuilder endSessionCallbackUrlBuilder) {
    Supplier<OpenIdProviderMetadata> metadataSupplier = SupplierUtil.memoized(openIdProviderMetadata::get);
    EndSessionEndpoint endSessionEndpoint = null;
    if (openIdClientConfiguration.getEndSession().isEnabled()) {
        endSessionEndpoint = endSessionEndpointResolver.resolve(clientConfiguration, metadataSupplier, endSessionCallbackUrlBuilder).orElse(null);
    }
    return new DefaultOpenIdClient(clientConfiguration, metadataSupplier, authenticationMapper, redirectUrlBuilder, authorizationResponseHandler, beanContext, endSessionEndpoint);
}
Also used : EndSessionEndpoint(io.micronaut.security.oauth2.endpoint.endsession.request.EndSessionEndpoint) Requires(io.micronaut.context.annotation.Requires) EachBean(io.micronaut.context.annotation.EachBean)

Example 13 with OauthClientConfiguration

use of io.micronaut.security.oauth2.configuration.OauthClientConfiguration in project micronaut-security by micronaut-projects.

the class OpenIdClientFactory method overrideFromConfig.

private void overrideFromConfig(DefaultOpenIdProviderMetadata configuration, OpenIdClientConfiguration openIdClientConfiguration, OauthClientConfiguration oauthClientConfiguration) {
    openIdClientConfiguration.getJwksUri().ifPresent(configuration::setJwksUri);
    oauthClientConfiguration.getIntrospection().ifPresent(introspection -> {
        introspection.getUrl().ifPresent(configuration::setIntrospectionEndpoint);
        introspection.getAuthMethod().ifPresent(authMethod -> configuration.setIntrospectionEndpointAuthMethodsSupported(Collections.singletonList(authMethod.toString())));
    });
    oauthClientConfiguration.getRevocation().ifPresent(revocation -> {
        revocation.getUrl().ifPresent(configuration::setRevocationEndpoint);
        revocation.getAuthMethod().ifPresent(authMethod -> configuration.setRevocationEndpointAuthMethodsSupported(Collections.singletonList(authMethod.toString())));
    });
    openIdClientConfiguration.getRegistration().flatMap(EndpointConfiguration::getUrl).ifPresent(configuration::setRegistrationEndpoint);
    openIdClientConfiguration.getUserInfo().flatMap(EndpointConfiguration::getUrl).ifPresent(configuration::setUserinfoEndpoint);
    openIdClientConfiguration.getAuthorization().flatMap(EndpointConfiguration::getUrl).ifPresent(configuration::setAuthorizationEndpoint);
    openIdClientConfiguration.getToken().ifPresent(token -> {
        token.getUrl().ifPresent(configuration::setTokenEndpoint);
        token.getAuthMethod().ifPresent(authMethod -> configuration.setTokenEndpointAuthMethodsSupported(Collections.singletonList(authMethod.toString())));
    });
    EndSessionEndpointConfiguration endSession = openIdClientConfiguration.getEndSession();
    if (endSession.isEnabled()) {
        endSession.getUrl().ifPresent(configuration::setEndSessionEndpoint);
    }
}
Also used : EndSessionEndpointConfiguration(io.micronaut.security.oauth2.configuration.endpoints.EndSessionEndpointConfiguration)

Example 14 with OauthClientConfiguration

use of io.micronaut.security.oauth2.configuration.OauthClientConfiguration in project micronaut-security by micronaut-projects.

the class DefaultOauthAuthorizationResponseHandler method handle.

@Override
public Publisher<AuthenticationResponse> handle(AuthorizationResponse authorizationResponse, OauthClientConfiguration clientConfiguration, OauthAuthenticationMapper authenticationMapper, SecureEndpoint tokenEndpoint) {
    State state;
    if (stateValidator != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Validating state found in the authorization response from provider [{}]", clientConfiguration.getName());
        }
        state = authorizationResponse.getState();
        try {
            stateValidator.validate(authorizationResponse.getCallbackRequest(), state);
        } catch (InvalidStateException e) {
            return Flux.just(new AuthenticationFailed("State validation failed: " + e.getMessage()));
        }
    } else {
        state = null;
        if (LOG.isTraceEnabled()) {
            LOG.trace("Skipping state validation, no state validator found");
        }
    }
    OauthCodeTokenRequestContext context = new OauthCodeTokenRequestContext(authorizationResponse, tokenEndpoint, clientConfiguration);
    return Flux.from(tokenEndpointClient.sendRequest(context)).switchMap(response -> {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Token endpoint returned a success response. Creating a user details");
        }
        return Flux.from(authenticationMapper.createAuthenticationResponse(response, state)).map(AuthenticationResponse.class::cast);
    });
}
Also used : State(io.micronaut.security.oauth2.endpoint.authorization.state.State) AuthenticationFailed(io.micronaut.security.authentication.AuthenticationFailed) InvalidStateException(io.micronaut.security.oauth2.endpoint.authorization.state.InvalidStateException) OauthCodeTokenRequestContext(io.micronaut.security.oauth2.endpoint.token.request.context.OauthCodeTokenRequestContext) AuthenticationResponse(io.micronaut.security.authentication.AuthenticationResponse)

Example 15 with OauthClientConfiguration

use of io.micronaut.security.oauth2.configuration.OauthClientConfiguration in project micronaut-security by micronaut-projects.

the class DefaultOpenIdTokenResponseValidator method validateClaims.

/**
 * @param clientConfiguration The OAuth 2.0 client configuration
 * @param openIdProviderMetadata The OpenID provider metadata
 * @param jwt JWT with valida signature
 * @param nonce The persisted nonce value
 * @return the same JWT supplied as a parameter if the claims validation were succesful or empty if not.
 */
@NonNull
protected Optional<JWT> validateClaims(@NonNull OauthClientConfiguration clientConfiguration, @NonNull OpenIdProviderMetadata openIdProviderMetadata, @NonNull JWT jwt, @Nullable String nonce) {
    try {
        JWTClaimsSet claimsSet = jwt.getJWTClaimsSet();
        OpenIdClaims claims = new JWTOpenIdClaims(claimsSet);
        if (genericJwtClaimsValidators.stream().allMatch(validator -> validator.validate(claims, null))) {
            if (openIdClaimsValidators.stream().allMatch(validator -> validator.validate(claims, clientConfiguration, openIdProviderMetadata))) {
                if (nonceClaimValidator == null) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Skipping nonce validation because no bean of type {} present. ", NonceClaimValidator.class.getSimpleName());
                    }
                    return Optional.of(jwt);
                }
                if (nonceClaimValidator.validate(claims, clientConfiguration, openIdProviderMetadata, nonce)) {
                    return Optional.of(jwt);
                } else if (LOG.isErrorEnabled()) {
                    LOG.error("Nonce {} validation failed for claims {}", nonce, claims.getClaims().keySet().stream().map(key -> key + "=" + claims.getClaims().get(key)).collect(Collectors.joining(", ", "{", "}")));
                }
            } else if (LOG.isErrorEnabled()) {
                LOG.error("JWT OpenID specific claims validation failed for provider [{}]", clientConfiguration.getName());
            }
        } else if (LOG.isErrorEnabled()) {
            LOG.error("JWT generic claims validation failed for provider [{}]", clientConfiguration.getName());
        }
    } catch (ParseException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Failed to parse the JWT returned from provider [{}]", clientConfiguration.getName(), e);
        }
    }
    return Optional.empty();
}
Also used : JwkValidator(io.micronaut.security.token.jwt.signature.jwks.JwkValidator) Logger(org.slf4j.Logger) Collection(java.util.Collection) JWTOpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.JWTOpenIdClaims) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LoggerFactory(org.slf4j.LoggerFactory) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JwksSignatureConfigurationProperties(io.micronaut.security.token.jwt.signature.jwks.JwksSignatureConfigurationProperties) Singleton(jakarta.inject.Singleton) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration) JwksSignature(io.micronaut.security.token.jwt.signature.jwks.JwksSignature) Collectors(java.util.stream.Collectors) OpenIdProviderMetadata(io.micronaut.security.oauth2.client.OpenIdProviderMetadata) NonNull(io.micronaut.core.annotation.NonNull) OpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.OpenIdClaims) GenericJwtClaimsValidator(io.micronaut.security.token.jwt.validator.GenericJwtClaimsValidator) JWT(com.nimbusds.jwt.JWT) Nullable(io.micronaut.core.annotation.Nullable) JwtValidator(io.micronaut.security.token.jwt.validator.JwtValidator) Map(java.util.Map) OpenIdTokenResponse(io.micronaut.security.oauth2.endpoint.token.response.OpenIdTokenResponse) Optional(java.util.Optional) ParseException(java.text.ParseException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWTOpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.JWTOpenIdClaims) OpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.OpenIdClaims) JWTOpenIdClaims(io.micronaut.security.oauth2.endpoint.token.response.JWTOpenIdClaims) ParseException(java.text.ParseException) NonNull(io.micronaut.core.annotation.NonNull)

Aggregations

OauthClientConfiguration (io.micronaut.security.oauth2.configuration.OauthClientConfiguration)9 BeanContext (io.micronaut.context.BeanContext)7 ApplicationContext (io.micronaut.context.ApplicationContext)5 AnnotationMetadataProvider (io.micronaut.core.annotation.AnnotationMetadataProvider)5 Named (io.micronaut.core.naming.Named)5 ValueResolver (io.micronaut.core.value.ValueResolver)5 JWT (com.nimbusds.jwt.JWT)2 EachBean (io.micronaut.context.annotation.EachBean)2 Requires (io.micronaut.context.annotation.Requires)2 NonNull (io.micronaut.core.annotation.NonNull)2 Nullable (io.micronaut.core.annotation.Nullable)2 SupplierUtil (io.micronaut.core.util.SupplierUtil)2 HttpClient (io.micronaut.http.client.HttpClient)2 OpenIdProviderMetadata (io.micronaut.security.oauth2.client.OpenIdProviderMetadata)2 OpenIdClientConfiguration (io.micronaut.security.oauth2.configuration.OpenIdClientConfiguration)2 EndSessionEndpointConfiguration (io.micronaut.security.oauth2.configuration.endpoints.EndSessionEndpointConfiguration)2 AuthenticationMethod (io.micronaut.security.oauth2.endpoint.AuthenticationMethod)2 State (io.micronaut.security.oauth2.endpoint.authorization.state.State)2 EndSessionEndpoint (io.micronaut.security.oauth2.endpoint.endsession.request.EndSessionEndpoint)2 DefaultOpenIdAuthenticationMapper (io.micronaut.security.oauth2.endpoint.token.response.DefaultOpenIdAuthenticationMapper)2