Search in sources :

Example 1 with OpenIdClientConfiguration

use of io.micronaut.security.oauth2.configuration.OpenIdClientConfiguration 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 OpenIdClientConfiguration

use of io.micronaut.security.oauth2.configuration.OpenIdClientConfiguration 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 3 with OpenIdClientConfiguration

use of io.micronaut.security.oauth2.configuration.OpenIdClientConfiguration 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 4 with OpenIdClientConfiguration

use of io.micronaut.security.oauth2.configuration.OpenIdClientConfiguration 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)

Aggregations

BeanContext (io.micronaut.context.BeanContext)2 EachBean (io.micronaut.context.annotation.EachBean)2 Requires (io.micronaut.context.annotation.Requires)2 OauthClientConfiguration (io.micronaut.security.oauth2.configuration.OauthClientConfiguration)2 OpenIdClientConfiguration (io.micronaut.security.oauth2.configuration.OpenIdClientConfiguration)2 EndSessionEndpointConfiguration (io.micronaut.security.oauth2.configuration.endpoints.EndSessionEndpointConfiguration)2 EndSessionEndpoint (io.micronaut.security.oauth2.endpoint.endsession.request.EndSessionEndpoint)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ApplicationContext (io.micronaut.context.ApplicationContext)1 BeanProvider (io.micronaut.context.BeanProvider)1 Factory (io.micronaut.context.annotation.Factory)1 Parameter (io.micronaut.context.annotation.Parameter)1 BeanInstantiationException (io.micronaut.context.exceptions.BeanInstantiationException)1 AnnotationMetadataProvider (io.micronaut.core.annotation.AnnotationMetadataProvider)1 Internal (io.micronaut.core.annotation.Internal)1 Nullable (io.micronaut.core.annotation.Nullable)1 Named (io.micronaut.core.naming.Named)1 Argument (io.micronaut.core.type.Argument)1 StringUtils (io.micronaut.core.util.StringUtils)1 SupplierUtil (io.micronaut.core.util.SupplierUtil)1