Search in sources :

Example 6 with OauthClientConfiguration

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

the class DefaultOpenIdAuthorizationResponseHandler method validateOpenIdTokenResponse.

/**
 * @param nonce Nonce
 * @param clientConfiguration The client configuration
 * @param openIdProviderMetadata The provider metadata
 * @param openIdTokenResponse OpenID token response
 * @param authenticationMapper The user details mapper
 * @param state State
 * @return An Authentication response if the open id token could  be validated
 * @throws ParseException If the payload of the JWT doesn't represent a valid JSON object and a JWT claims set.
 */
private Optional<AuthenticationResponse> validateOpenIdTokenResponse(String nonce, OauthClientConfiguration clientConfiguration, OpenIdProviderMetadata openIdProviderMetadata, OpenIdTokenResponse openIdTokenResponse, @Nullable OpenIdAuthenticationMapper authenticationMapper, @Nullable State state) throws ParseException {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Token endpoint returned a success response. Validating the JWT");
    }
    Optional<JWT> jwt = tokenResponseValidator.validate(clientConfiguration, openIdProviderMetadata, openIdTokenResponse, nonce);
    if (jwt.isPresent()) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Token validation succeeded. Creating a user details");
        }
        OpenIdClaims claims = new JWTOpenIdClaims(jwt.get().getJWTClaimsSet());
        OpenIdAuthenticationMapper openIdAuthenticationMapper = authenticationMapper != null ? authenticationMapper : defaultAuthenticationMapper;
        return Optional.of(openIdAuthenticationMapper.createAuthenticationResponse(clientConfiguration.getName(), openIdTokenResponse, claims, state));
    }
    return Optional.empty();
}
Also used : JWT(com.nimbusds.jwt.JWT) 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) DefaultOpenIdAuthenticationMapper(io.micronaut.security.oauth2.endpoint.token.response.DefaultOpenIdAuthenticationMapper) OpenIdAuthenticationMapper(io.micronaut.security.oauth2.endpoint.token.response.OpenIdAuthenticationMapper)

Example 7 with OauthClientConfiguration

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

the class ClientCredentialsEnabled 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));
            String failureMessage = "Client credentials is disabled for the client [" + name + "]";
            if (clientConfiguration.isEnabled()) {
                Optional<ClientCredentialsConfiguration> clientCredentialsConfiguration = clientConfiguration.getClientCredentials();
                if (!clientCredentialsConfiguration.isPresent() || clientCredentialsConfiguration.get().isEnabled()) {
                    return true;
                } else {
                    context.fail(failureMessage);
                    return false;
                }
            } else {
                context.fail(failureMessage);
                return false;
            }
        }
    }
    return true;
}
Also used : BeanContext(io.micronaut.context.BeanContext) Named(io.micronaut.core.naming.Named) ApplicationContext(io.micronaut.context.ApplicationContext) ValueResolver(io.micronaut.core.value.ValueResolver) AnnotationMetadataProvider(io.micronaut.core.annotation.AnnotationMetadataProvider) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration)

Example 8 with OauthClientConfiguration

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

the class OauthPasswordAuthenticationProvider method getTokenEndpoint.

/**
 * Builds the secure endpoint from the client configuration.
 *
 * @param clientConfiguration The client configuration
 * @return The token endpoint
 */
protected SecureEndpoint getTokenEndpoint(OauthClientConfiguration clientConfiguration) {
    SecureEndpointConfiguration endpointConfiguration = clientConfiguration.getToken().orElseThrow(() -> new IllegalArgumentException("Token endpoint configuration is missing for provider [" + clientConfiguration.getName() + "]"));
    List<AuthenticationMethod> authMethodsSupported = Collections.singletonList(endpointConfiguration.getAuthMethod().orElse(AuthenticationMethod.CLIENT_SECRET_BASIC));
    String url = endpointConfiguration.getUrl().orElseThrow(() -> new IllegalArgumentException("Token endpoint URL is null for provider [" + clientConfiguration.getName() + "]"));
    return new DefaultSecureEndpoint(url, authMethodsSupported);
}
Also used : SecureEndpointConfiguration(io.micronaut.security.oauth2.configuration.endpoints.SecureEndpointConfiguration) DefaultSecureEndpoint(io.micronaut.security.oauth2.endpoint.DefaultSecureEndpoint) AuthenticationMethod(io.micronaut.security.oauth2.endpoint.AuthenticationMethod)

Example 9 with OauthClientConfiguration

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

the class PasswordGrantCondition 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));
            String failureMsgPrefix = "Skipped password grant flow for provider [" + name;
            if (clientConfiguration.isEnabled()) {
                if (clientConfiguration.getGrantType() == GrantType.PASSWORD) {
                    if (clientConfiguration.getToken().isPresent()) {
                        if (beanContext.containsBean(OauthAuthenticationMapper.class, Qualifiers.byName(name))) {
                            return true;
                        } else {
                            context.fail(failureMsgPrefix + "] because no user details mapper could be found");
                        }
                    } else if (clientConfiguration.getOpenid().isPresent()) {
                        boolean hasOpenIdProviderMetadata = beanContext.containsBean(OpenIdProviderMetadata.class, Qualifiers.byName(name));
                        boolean hasTokenResponseValidator = beanContext.containsBean(OpenIdTokenResponseValidator.class);
                        if (hasOpenIdProviderMetadata && hasTokenResponseValidator) {
                            boolean hasAuthenticationMapper = beanContext.containsBean(OpenIdAuthenticationMapper.class, Qualifiers.byName(name));
                            if (!hasAuthenticationMapper) {
                                hasAuthenticationMapper = beanContext.containsBean(DefaultOpenIdAuthenticationMapper.class);
                            }
                            if (hasAuthenticationMapper) {
                                return true;
                            } else {
                                context.fail(failureMsgPrefix + "] because no user details mapper could be found");
                            }
                        } else {
                            context.fail(failureMsgPrefix + "] because no provider metadata and token validator could be found");
                        }
                    } else {
                        context.fail(failureMsgPrefix + "] because no token endpoint or openid configuration was found");
                    }
                } else {
                    context.fail(failureMsgPrefix + "] because the grant type is not 'password'");
                }
            } else {
                context.fail(failureMsgPrefix + "] because the configuration is disabled");
            }
            return false;
        }
    }
    return true;
}
Also used : BeanContext(io.micronaut.context.BeanContext) Named(io.micronaut.core.naming.Named) ApplicationContext(io.micronaut.context.ApplicationContext) OpenIdTokenResponseValidator(io.micronaut.security.oauth2.endpoint.token.response.validation.OpenIdTokenResponseValidator) ValueResolver(io.micronaut.core.value.ValueResolver) DefaultOpenIdAuthenticationMapper(io.micronaut.security.oauth2.endpoint.token.response.DefaultOpenIdAuthenticationMapper) OpenIdAuthenticationMapper(io.micronaut.security.oauth2.endpoint.token.response.OpenIdAuthenticationMapper) AnnotationMetadataProvider(io.micronaut.core.annotation.AnnotationMetadataProvider) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration) OpenIdProviderMetadata(io.micronaut.security.oauth2.client.OpenIdProviderMetadata)

Example 10 with OauthClientConfiguration

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

the class DefaultTokenEndpointClient method secureRequest.

/**
 * Secures the request according to the context's endpoint supported authentication
 * methods.
 *
 * @param request Token endpoint Request
 * @param requestContext The request context
 * @param <G> The token request grant or body
 * @param <R> The token response type
 */
protected <G, R extends TokenResponse> void secureRequest(@NonNull MutableHttpRequest<G> request, TokenRequestContext<G, R> requestContext) {
    List<AuthenticationMethod> authMethodsSupported = requestContext.getEndpoint().getSupportedAuthenticationMethods().orElseGet(() -> Collections.singletonList(AuthenticationMethod.CLIENT_SECRET_BASIC));
    OauthClientConfiguration clientConfiguration = requestContext.getClientConfiguration();
    if (LOG.isTraceEnabled()) {
        LOG.trace("The token endpoint supports [{}] authentication methods", authMethodsSupported);
    }
    if (authMethodsSupported.contains(AuthenticationMethod.CLIENT_SECRET_BASIC)) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using client_secret_basic authentication. Adding an Authorization header");
        }
        request.basicAuth(clientConfiguration.getClientId(), clientConfiguration.getClientSecret());
    } else if (authMethodsSupported.contains(AuthenticationMethod.CLIENT_SECRET_POST)) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using client_secret_post authentication. The client_id and client_secret will be present in the body");
        }
        request.getBody().filter(SecureGrant.class::isInstance).map(SecureGrant.class::cast).ifPresent(body -> {
            body.setClientId(clientConfiguration.getClientId());
            body.setClientSecret(clientConfiguration.getClientSecret());
        });
    } else {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Unsupported or no authentication method. The client_id will be present in the body");
        }
        request.getBody().filter(SecureGrant.class::isInstance).map(SecureGrant.class::cast).ifPresent(body -> body.setClientId(clientConfiguration.getClientId()));
    }
}
Also used : Logger(org.slf4j.Logger) BeanContext(io.micronaut.context.BeanContext) Publisher(org.reactivestreams.Publisher) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LoggerFactory(org.slf4j.LoggerFactory) HttpClientConfiguration(io.micronaut.http.client.HttpClientConfiguration) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) Singleton(jakarta.inject.Singleton) AuthenticationMethod(io.micronaut.security.oauth2.endpoint.AuthenticationMethod) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration) Supplier(java.util.function.Supplier) TokenResponse(io.micronaut.security.oauth2.endpoint.token.response.TokenResponse) NonNull(io.micronaut.core.annotation.NonNull) List(java.util.List) SecureGrant(io.micronaut.security.oauth2.grants.SecureGrant) MediaType(io.micronaut.http.MediaType) Optional(java.util.Optional) HttpRequest(io.micronaut.http.HttpRequest) SupplierUtil(io.micronaut.core.util.SupplierUtil) MutableHttpRequest(io.micronaut.http.MutableHttpRequest) HttpClient(io.micronaut.http.client.HttpClient) LoadBalancer(io.micronaut.http.client.LoadBalancer) Collections(java.util.Collections) TokenRequestContext(io.micronaut.security.oauth2.endpoint.token.request.context.TokenRequestContext) SecureGrant(io.micronaut.security.oauth2.grants.SecureGrant) AuthenticationMethod(io.micronaut.security.oauth2.endpoint.AuthenticationMethod) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration)

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