Search in sources :

Example 66 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest in project spring-security by spring-projects.

the class HttpSessionOAuth2AuthorizationRequestRepositoryTests method saveAuthorizationRequestWhenNullThenRemoved.

@Test
public void saveAuthorizationRequestWhenNullThenRemoved() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build();
    this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
    request.addParameter(OAuth2ParameterNames.STATE, authorizationRequest.getState());
    this.authorizationRequestRepository.saveAuthorizationRequest(null, request, response);
    OAuth2AuthorizationRequest loadedAuthorizationRequest = this.authorizationRequestRepository.loadAuthorizationRequest(request);
    assertThat(loadedAuthorizationRequest).isNull();
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 67 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest in project dhis2-core by dhis2.

the class DhisCustomAuthorizationRequestResolver method customizeAuthorizationRequest.

private OAuth2AuthorizationRequest customizeAuthorizationRequest(OAuth2AuthorizationRequest req, String clientRegistrationId) {
    if (req == null) {
        return null;
    }
    Map<String, Object> attributes = new HashMap<>(req.getAttributes());
    Map<String, Object> additionalParameters = new HashMap<>(req.getAdditionalParameters());
    ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
    if (clientRegistration == null) {
        return null;
    }
    Map<String, Object> configurationMetadata = clientRegistration.getProviderDetails().getConfigurationMetadata();
    boolean enablePkce = Boolean.parseBoolean((String) configurationMetadata.get(ENABLE_PKCE));
    if (enablePkce) {
        addPkceParameters(attributes, additionalParameters);
    }
    @SuppressWarnings("unchecked") Map<String, Object> extraRequestParameters = (Map<String, Object>) configurationMetadata.get(EXTRA_REQUEST_PARAMETERS);
    if (extraRequestParameters != null && !extraRequestParameters.isEmpty()) {
        for (String key : extraRequestParameters.keySet()) {
            String value = (String) extraRequestParameters.get(key);
            additionalParameters.put(key, value);
        }
    }
    return OAuth2AuthorizationRequest.from(req).attributes(attributes).additionalParameters(additionalParameters).build();
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map)

Example 68 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest in project midpoint by Evolveum.

the class OidcLoginAuthenticationFilter method attemptAuthentication.

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    MultiValueMap<String, String> params = toMultiMap(request.getParameterMap());
    if (!isAuthorizationResponse(params)) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_REQUEST_ERROR_CODE);
        throw new OAuth2AuthenticationException(oauth2Error, "web.security.provider.invalid");
    } else {
        OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.removeAuthorizationRequest(request, response);
        if (authorizationRequest == null) {
            OAuth2Error oauth2Error = new OAuth2Error(AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE);
            throw new OAuth2AuthenticationException(oauth2Error, "web.security.provider.invalid");
        } else {
            String registrationId = authorizationRequest.getAttribute("registration_id");
            ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
            if (clientRegistration == null) {
                OAuth2Error oauth2Error = new OAuth2Error(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE, "Client Registration not found with Id: " + registrationId, null);
                throw new OAuth2AuthenticationException(oauth2Error, "web.security.provider.invalid");
            } else {
                String redirectUri = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)).replaceQuery(null).build().toUriString();
                OAuth2AuthorizationResponse authorizationResponse = convert(params, redirectUri);
                OAuth2LoginAuthenticationToken authenticationRequest = new OAuth2LoginAuthenticationToken(clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
                MidpointAuthentication authenticationResult = (MidpointAuthentication) this.getAuthenticationManager().authenticate(authenticationRequest);
                Assert.notNull(authenticationResult, "authentication result cannot be null");
                return authenticationResult;
            }
        }
    }
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)

Example 69 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest in project midpoint by Evolveum.

the class OidcAuthorizationRequestRedirectFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof MidpointAuthentication) {
        MidpointAuthentication mpAuthentication = (MidpointAuthentication) authentication;
        OidcClientModuleAuthenticationImpl moduleAuthentication = (OidcClientModuleAuthenticationImpl) mpAuthentication.getProcessingModuleAuthentication();
        try {
            OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver.resolve(request);
            if (authorizationRequest != null) {
                this.sendRedirectForAuthorization(request, response, authorizationRequest);
                moduleAuthentication.setRequestState(RequestState.SENDED);
                return;
            }
        } catch (Exception ex) {
            unsuccessfulAuthentication(request, response, new InternalAuthenticationServiceException("web.security.provider.invalid", ex));
            return;
        }
        try {
            filterChain.doFilter(request, response);
        } catch (IOException ex) {
            throw ex;
        } catch (Exception ex) {
            // Check to see if we need to handle ClientAuthorizationRequiredException
            Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(ex);
            ClientAuthorizationRequiredException authzEx = (ClientAuthorizationRequiredException) this.throwableAnalyzer.getFirstThrowableOfType(ClientAuthorizationRequiredException.class, causeChain);
            if (authzEx != null) {
                try {
                    OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver.resolve(request, authzEx.getClientRegistrationId());
                    if (authorizationRequest == null) {
                        throw authzEx;
                    }
                    this.sendRedirectForAuthorization(request, response, authorizationRequest);
                    moduleAuthentication.setRequestState(RequestState.SENDED);
                    this.requestCache.saveRequest(request, response);
                } catch (Exception failed) {
                    unsuccessfulAuthentication(request, response, new InternalAuthenticationServiceException("web.security.provider.invalid", failed));
                }
                return;
            }
            if (ex instanceof ServletException) {
                throw (ServletException) ex;
            }
            if (ex instanceof RuntimeException) {
                throw (RuntimeException) ex;
            }
            throw new RuntimeException(ex);
        }
    } else {
        throw new AuthenticationServiceException("Unsupported type of Authentication");
    }
}
Also used : ServletException(javax.servlet.ServletException) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) Authentication(org.springframework.security.core.Authentication) OidcClientModuleAuthenticationImpl(com.evolveum.midpoint.authentication.impl.module.authentication.OidcClientModuleAuthenticationImpl) ClientAuthorizationRequiredException(org.springframework.security.oauth2.client.ClientAuthorizationRequiredException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) IOException(java.io.IOException) MidpointAuthentication(com.evolveum.midpoint.authentication.api.config.MidpointAuthentication) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) ServletException(javax.servlet.ServletException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) AuthenticationException(org.springframework.security.core.AuthenticationException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) ClientAuthorizationRequiredException(org.springframework.security.oauth2.client.ClientAuthorizationRequiredException) IOException(java.io.IOException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException)

Example 70 with OAuth2AuthorizationRequest

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest in project thingsboard by thingsboard.

the class CustomOAuth2AuthorizationRequestResolver method resolve.

@SuppressWarnings("deprecation")
private OAuth2AuthorizationRequest resolve(HttpServletRequest request, String registrationId, String redirectUriAction, String appPackage, String appToken) {
    if (registrationId == null) {
        return null;
    }
    ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
    if (clientRegistration == null) {
        throw new IllegalArgumentException("Invalid Client Registration with Id: " + registrationId);
    }
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId());
    if (!StringUtils.isEmpty(appPackage)) {
        if (StringUtils.isEmpty(appToken)) {
            throw new IllegalArgumentException("Invalid application token.");
        } else {
            String appSecret = this.oAuth2Service.findAppSecret(UUID.fromString(registrationId), appPackage);
            if (StringUtils.isEmpty(appSecret)) {
                throw new IllegalArgumentException("Invalid package: " + appPackage + ". No application secret found for Client Registration with given application package.");
            }
            String callbackUrlScheme = this.oAuth2AppTokenFactory.validateTokenAndGetCallbackUrlScheme(appPackage, appToken, appSecret);
            attributes.put(TbOAuth2ParameterNames.CALLBACK_URL_SCHEME, callbackUrlScheme);
        }
    }
    OAuth2AuthorizationRequest.Builder builder;
    if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(clientRegistration.getAuthorizationGrantType())) {
        builder = OAuth2AuthorizationRequest.authorizationCode();
        Map<String, Object> additionalParameters = new HashMap<>();
        if (!CollectionUtils.isEmpty(clientRegistration.getScopes()) && clientRegistration.getScopes().contains(OidcScopes.OPENID)) {
            // Section 3.1.2.1 Authentication Request - https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
            // scope
            // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
            addNonceParameters(attributes, additionalParameters);
        }
        if (ClientAuthenticationMethod.NONE.equals(clientRegistration.getClientAuthenticationMethod())) {
            addPkceParameters(attributes, additionalParameters);
        }
        builder.additionalParameters(additionalParameters);
    } else if (AuthorizationGrantType.IMPLICIT.equals(clientRegistration.getAuthorizationGrantType())) {
        builder = OAuth2AuthorizationRequest.implicit();
    } else {
        throw new IllegalArgumentException("Invalid Authorization Grant Type (" + clientRegistration.getAuthorizationGrantType().getValue() + ") for Client Registration with Id: " + clientRegistration.getRegistrationId());
    }
    String redirectUriStr = expandRedirectUri(request, clientRegistration, redirectUriAction);
    return builder.clientId(clientRegistration.getClientId()).authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri()).redirectUri(redirectUriStr).scopes(clientRegistration.getScopes()).state(this.stateGenerator.generateKey()).attributes(attributes).build();
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) HashMap(java.util.HashMap) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Aggregations

OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)137 Test (org.junit.jupiter.api.Test)112 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)52 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)49 HashMap (java.util.HashMap)26 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)25 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)24 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)22 Authentication (org.springframework.security.core.Authentication)19 MockServerHttpRequest (org.springframework.mock.http.server.reactive.MockServerHttpRequest)18 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)17 ServerWebExchange (org.springframework.web.server.ServerWebExchange)13 OAuth2ParameterNames (org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames)12 MockServerWebExchange (org.springframework.mock.web.server.MockServerWebExchange)11 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)11 BeforeEach (org.junit.jupiter.api.BeforeEach)10 HttpRequestResponseHolder (org.springframework.security.web.context.HttpRequestResponseHolder)10 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)10 Map (java.util.Map)9 Mono (reactor.core.publisher.Mono)9