Search in sources :

Example 1 with OauthClientConfiguration

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

the class OpenIdClientFactory method openIdConfiguration.

/**
 * Retrieves OpenID configuration from the provided issuer.
 *
 * @param oauthClientConfiguration The client configuration
 * @param openIdClientConfiguration The openid client configuration
 * @param issuerClient The client to request the metadata
 * @return The OpenID configuration
 */
@EachBean(OpenIdClientConfiguration.class)
DefaultOpenIdProviderMetadata openIdConfiguration(@Parameter OauthClientConfiguration oauthClientConfiguration, @Parameter OpenIdClientConfiguration openIdClientConfiguration, @Client HttpClient issuerClient) {
    DefaultOpenIdProviderMetadata providerMetadata = openIdClientConfiguration.getIssuer().map(issuer -> {
        try {
            URL configurationUrl = new URL(issuer, StringUtils.prependUri(issuer.getPath(), openIdClientConfiguration.getConfigurationPath()));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Sending request for OpenID configuration for provider [{}] to URL [{}]", openIdClientConfiguration.getName(), configurationUrl);
            }
            // TODO NOSONAR this returns ReadTimeoutException - return issuerClient.toBlocking().retrieve(configurationUrl.toString(), DefaultOpenIdProviderMetadata.class);
            String json = issuerClient.toBlocking().retrieve(configurationUrl.toString(), String.class);
            return jsonMapper.readValue(json.getBytes(StandardCharsets.UTF_8), Argument.of(DefaultOpenIdProviderMetadata.class));
        } catch (HttpClientResponseException e) {
            throw new BeanInstantiationException("Failed to retrieve OpenID configuration for " + openIdClientConfiguration.getName(), e);
        } catch (MalformedURLException e) {
            throw new BeanInstantiationException("Failure parsing issuer URL " + issuer.toString(), e);
        } catch (IOException e) {
            throw new BeanInstantiationException("JSON Processing Exception parsing issuer URL returned JSON " + issuer.toString(), e);
        }
    }).orElse(new DefaultOpenIdProviderMetadata());
    overrideFromConfig(providerMetadata, openIdClientConfiguration, oauthClientConfiguration);
    return providerMetadata;
}
Also used : Parameter(io.micronaut.context.annotation.Parameter) EndSessionEndpointResolver(io.micronaut.security.oauth2.endpoint.endsession.request.EndSessionEndpointResolver) BeanContext(io.micronaut.context.BeanContext) URL(java.net.URL) JacksonDatabindMapper(io.micronaut.jackson.databind.JacksonDatabindMapper) LoggerFactory(org.slf4j.LoggerFactory) EndSessionCallbackUrlBuilder(io.micronaut.security.oauth2.endpoint.endsession.response.EndSessionCallbackUrlBuilder) Client(io.micronaut.http.client.annotation.Client) Internal(io.micronaut.core.annotation.Internal) Supplier(java.util.function.Supplier) BeanInstantiationException(io.micronaut.context.exceptions.BeanInstantiationException) EachBean(io.micronaut.context.annotation.EachBean) Nullable(io.micronaut.core.annotation.Nullable) JsonMapper(io.micronaut.json.JsonMapper) Requires(io.micronaut.context.annotation.Requires) HttpClientResponseException(io.micronaut.http.client.exceptions.HttpClientResponseException) Argument(io.micronaut.core.type.Argument) SupplierUtil(io.micronaut.core.util.SupplierUtil) HttpClient(io.micronaut.http.client.HttpClient) EndSessionEndpoint(io.micronaut.security.oauth2.endpoint.endsession.request.EndSessionEndpoint) OpenIdClientConfiguration(io.micronaut.security.oauth2.configuration.OpenIdClientConfiguration) OpenIdClientCondition(io.micronaut.security.oauth2.client.condition.OpenIdClientCondition) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) AuthorizationRedirectHandler(io.micronaut.security.oauth2.endpoint.authorization.request.AuthorizationRedirectHandler) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration) StandardCharsets(java.nio.charset.StandardCharsets) StringUtils(io.micronaut.core.util.StringUtils) EndSessionEndpointConfiguration(io.micronaut.security.oauth2.configuration.endpoints.EndSessionEndpointConfiguration) Factory(io.micronaut.context.annotation.Factory) EndpointConfiguration(io.micronaut.security.oauth2.configuration.endpoints.EndpointConfiguration) BeanProvider(io.micronaut.context.BeanProvider) Inject(jakarta.inject.Inject) OpenIdAuthenticationMapper(io.micronaut.security.oauth2.endpoint.token.response.OpenIdAuthenticationMapper) Collections(java.util.Collections) OpenIdAuthorizationResponseHandler(io.micronaut.security.oauth2.endpoint.authorization.response.OpenIdAuthorizationResponseHandler) MalformedURLException(java.net.MalformedURLException) HttpClientResponseException(io.micronaut.http.client.exceptions.HttpClientResponseException) BeanInstantiationException(io.micronaut.context.exceptions.BeanInstantiationException) IOException(java.io.IOException) URL(java.net.URL) EachBean(io.micronaut.context.annotation.EachBean)

Example 2 with OauthClientConfiguration

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

the class ClientCredentialsHeaderPropagatorEnabled 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));
            Optional<ClientCredentialsHeaderTokenPropagatorConfiguration> headerTokenConfiguration = clientConfiguration.getClientCredentials().flatMap(ClientCredentialsConfiguration::getHeaderPropagation);
            if (headerTokenConfiguration.isPresent()) {
                if (headerTokenConfiguration.get().isEnabled()) {
                    return true;
                } else {
                    context.fail("Client credentials header token handler is disabled");
                    return false;
                }
            } else {
                context.fail("Client credentials header token handler disabled due to a lack of configuration");
                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) ClientCredentialsConfiguration(io.micronaut.security.oauth2.client.clientcredentials.ClientCredentialsConfiguration) AnnotationMetadataProvider(io.micronaut.core.annotation.AnnotationMetadataProvider) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration)

Example 3 with OauthClientConfiguration

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

the class ClientCredentialsHttpClientFilter method doFilter.

@Override
public Publisher<? extends HttpResponse<?>> doFilter(MutableHttpRequest<?> request, ClientFilterChain chain) {
    Optional<OauthClientConfiguration> oauthClientOptional = getClientConfiguration(request);
    if (!oauthClientOptional.isPresent()) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Did not find any OAuth 2.0 client which should decorate the request with an access token received from client credentials request");
        }
        return chain.proceed(request);
    }
    OauthClientConfiguration oauthClient = oauthClientOptional.get();
    Optional<ClientCredentialsClient> clientCredentialsClientOptional = getClient(oauthClient);
    if (!clientCredentialsClientOptional.isPresent()) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Could not retrieve client credentials client for OAuth 2.0 client {}", oauthClient.getName());
        }
        return chain.proceed(request);
    }
    ClientCredentialsTokenPropagator tokenHandler = getTokenHandler(oauthClient);
    return Flux.from(clientCredentialsClientOptional.get().requestToken(getScope(oauthClient))).map(TokenResponse::getAccessToken).switchMap(accessToken -> {
        if (StringUtils.isNotEmpty(accessToken)) {
            tokenHandler.writeToken(request, accessToken);
        }
        return chain.proceed(request);
    });
}
Also used : OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration) ClientCredentialsClient(io.micronaut.security.oauth2.client.clientcredentials.ClientCredentialsClient)

Example 4 with OauthClientConfiguration

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

the class OauthClientCondition 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 client creation for provider [" + name;
            if (clientConfiguration.isEnabled()) {
                if (clientConfiguration.getAuthorization().flatMap(EndpointConfiguration::getUrl).isPresent()) {
                    if (clientConfiguration.getToken().flatMap(EndpointConfiguration::getUrl).isPresent()) {
                        if (clientConfiguration.getGrantType() == GrantType.AUTHORIZATION_CODE) {
                            return true;
                        } else {
                            context.fail(failureMsgPrefix + "] because grant type is not authorization code");
                        }
                    } else {
                        context.fail(failureMsgPrefix + "] because no token endpoint is configured");
                    }
                } else {
                    context.fail(failureMsgPrefix + "] because no authorization endpoint is configured");
                }
            } 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) ValueResolver(io.micronaut.core.value.ValueResolver) AnnotationMetadataProvider(io.micronaut.core.annotation.AnnotationMetadataProvider) OauthClientConfiguration(io.micronaut.security.oauth2.configuration.OauthClientConfiguration)

Example 5 with OauthClientConfiguration

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

the class DefaultOpenIdAuthorizationResponseHandler method validateState.

/**
 * Validates the Authorization response state.
 * @param authorizationResponse The authorization response
 * @param clientConfiguration The client configuration
 * @throws InvalidStateException if the state did not pass validation
 */
private void validateState(OpenIdAuthorizationResponse authorizationResponse, OauthClientConfiguration clientConfiguration) throws InvalidStateException {
    if (stateValidator != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Validating state found in the authorization response from provider [{}]", clientConfiguration.getName());
        }
        State state = authorizationResponse.getState();
        stateValidator.validate(authorizationResponse.getCallbackRequest(), state);
    } else {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Skipping state validation, no state validator found");
        }
    }
}
Also used : State(io.micronaut.security.oauth2.endpoint.authorization.state.State)

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