All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.micronaut.security.oauth2.client.DefaultOpenIdClient Maven / Gradle / Ivy

/*
 * Copyright 2017-2023 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micronaut.security.oauth2.client;

import io.micronaut.context.BeanContext;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.convert.value.ConvertibleMultiValues;
import io.micronaut.core.util.SupplierUtil;
import io.micronaut.http.*;
import io.micronaut.security.authentication.Authentication;
import io.micronaut.security.authentication.AuthenticationResponse;
import io.micronaut.security.oauth2.configuration.OauthClientConfiguration;
import io.micronaut.security.oauth2.endpoint.SecureEndpoint;
import io.micronaut.security.oauth2.endpoint.authorization.request.AuthorizationRedirectHandler;
import io.micronaut.security.oauth2.endpoint.authorization.request.AuthorizationRequest;
import io.micronaut.security.oauth2.endpoint.authorization.request.OpenIdAuthorizationRequest;
import io.micronaut.security.oauth2.endpoint.authorization.response.AuthorizationErrorResponse;
import io.micronaut.security.oauth2.endpoint.authorization.response.AuthorizationErrorResponseException;
import io.micronaut.security.oauth2.endpoint.authorization.response.OpenIdAuthorizationResponse;
import io.micronaut.security.oauth2.endpoint.authorization.response.OpenIdAuthorizationResponseHandler;
import io.micronaut.security.oauth2.endpoint.endsession.request.EndSessionEndpoint;
import io.micronaut.security.oauth2.endpoint.token.response.OpenIdAuthenticationMapper;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;

import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

import static io.micronaut.security.oauth2.client.ClientUtils.getResponseData;

/**
 * The default implementation of {@link OpenIdClient}.
 *
 * @author James Kleeh
 * @since 1.2.0
 */
public class DefaultOpenIdClient implements OpenIdClient {

    private static final Logger LOG = LoggerFactory.getLogger(DefaultOpenIdClient.class);

    private final OauthClientConfiguration clientConfiguration;
    private final Supplier openIdProviderMetadata;
    private final OpenIdAuthenticationMapper authenticationMapper;
    private final AuthorizationRedirectHandler redirectUrlBuilder;
    private final OpenIdAuthorizationResponseHandler authorizationResponseHandler;
    private final Supplier tokenEndpoint;
    private final BeanContext beanContext;
    private final EndSessionEndpoint endSessionEndpoint;

    /**
     * @param clientConfiguration The client configuration
     * @param openIdProviderMetadata The provider metadata
     * @param authenticationMapper The user details mapper
     * @param redirectUrlBuilder The redirect URL builder
     * @param authorizationResponseHandler The authorization response handler
     * @param beanContext The bean context
     * @param endSessionEndpoint The end session request
     */
    public DefaultOpenIdClient(OauthClientConfiguration clientConfiguration,
                               Supplier openIdProviderMetadata,
                               @Nullable OpenIdAuthenticationMapper authenticationMapper,
                               AuthorizationRedirectHandler redirectUrlBuilder,
                               OpenIdAuthorizationResponseHandler authorizationResponseHandler,
                               BeanContext beanContext,
                               @Nullable EndSessionEndpoint endSessionEndpoint) {
        this.clientConfiguration = clientConfiguration;
        this.openIdProviderMetadata = openIdProviderMetadata;
        this.authenticationMapper = authenticationMapper;
        this.redirectUrlBuilder = redirectUrlBuilder;
        this.authorizationResponseHandler = authorizationResponseHandler;
        this.beanContext = beanContext;
        this.endSessionEndpoint = endSessionEndpoint;
        this.tokenEndpoint = SupplierUtil.memoized(() -> openIdProviderMetadata.get().tokenEndpoint());
    }

    @Override
    public String getName() {
        return clientConfiguration.getName();
    }

    @Override
    public boolean supportsEndSession() {
        return endSessionEndpoint != null;
    }

    @Override
    public Optional> endSessionRedirect(HttpRequest request, Authentication authentication) {

        if (LOG.isTraceEnabled()) {
            LOG.trace("Starting end session flow to provider [{}]", getName());
        }
        return Optional.ofNullable(endSessionEndpoint)
                .map(esr -> esr.getUrl(request, authentication))
                .map(url -> {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Redirecting to [{}]", url);
                    }
                    return HttpResponse.status(HttpStatus.FOUND)
                        .header(HttpHeaders.LOCATION, url);
                });
    }

    @Override
    public Publisher> authorizationRedirect(HttpRequest originating) {
        OpenIdProviderMetadata openIdProviderMetadataResolved = openIdProviderMetadata.get();
        AuthorizationRequest authorizationRequest = beanContext.createBean(OpenIdAuthorizationRequest.class, originating, clientConfiguration, openIdProviderMetadataResolved);
        String endpoint = openIdProviderMetadataResolved.getAuthorizationEndpoint();

        if (LOG.isTraceEnabled()) {
            LOG.trace("Starting authorization code grant flow to provider [{}]. Redirecting to [{}]", getName(), endpoint);
        }
        return Flux.just(redirectUrlBuilder.redirect(authorizationRequest, endpoint));
    }

    @Override
    public Publisher onCallback(HttpRequest> request) {
        ConvertibleMultiValues responseData = getResponseData(request);

        if (isErrorCallback(responseData)) {
            AuthorizationErrorResponse errorResponse = beanContext.createBean(AuthorizationErrorResponse.class, request);
            if (LOG.isTraceEnabled()) {
                LOG.trace("Received an authorization error response from provider [{}]. Error: [{}]", getName(), errorResponse.getError());
            }
            throw new AuthorizationErrorResponseException(errorResponse);
        } else {
            OpenIdAuthorizationResponse authorizationResponse = beanContext.createBean(OpenIdAuthorizationResponse.class, request);
            if (LOG.isTraceEnabled()) {
                LOG.trace("Received a successful authorization response from provider [{}]", getName());
            }
            return authorizationResponseHandler.handle(authorizationResponse,
                    clientConfiguration,
                    openIdProviderMetadata.get(),
                    authenticationMapper,
                    tokenEndpoint.get());
        }
    }

    /**
     * @param responseData The response data
     * @return True if the response indicates an error occurred.
     */
    protected boolean isErrorCallback(ConvertibleMultiValues responseData) {
        return responseData.contains("error");
    }

    /**
     * @return The token endpoint
     * @deprecated Not used.
     */
    @Deprecated(forRemoval = true)
    protected SecureEndpoint getTokenEndpoint() {
        return openIdProviderMetadata.get().tokenEndpoint();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy