Search in sources :

Example 21 with OAuth2AuthenticationException

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

the class OidcResourceServerModuleAuthentication method getRealmFroHeader.

public String getRealmFroHeader(AuthenticationException authException) {
    Map<String, String> parameters = new LinkedHashMap<>();
    if (authException instanceof OAuth2AuthenticationException) {
        OAuth2Error error = ((OAuth2AuthenticationException) authException).getError();
        parameters.put("error", error.getErrorCode());
        if (org.springframework.util.StringUtils.hasText(error.getDescription())) {
            parameters.put("error_description", error.getDescription());
        }
        if (org.springframework.util.StringUtils.hasText(error.getUri())) {
            parameters.put("error_uri", error.getUri());
        }
        if (error instanceof BearerTokenError) {
            BearerTokenError bearerTokenError = (BearerTokenError) error;
            if (StringUtils.hasText(bearerTokenError.getScope())) {
                parameters.put("scope", bearerTokenError.getScope());
            }
        }
    }
    StringBuilder wwwAuthenticate = new StringBuilder(super.getRealmFroHeader(authException));
    if (!parameters.isEmpty()) {
        parameters.forEach((key, value) -> {
            wwwAuthenticate.append(", ");
            wwwAuthenticate.append(key).append("=\"").append(value).append("\"");
        });
    }
    return wwwAuthenticate.toString();
}
Also used : OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) LinkedHashMap(java.util.LinkedHashMap)

Example 22 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException 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 23 with OAuth2AuthenticationException

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

the class OidcResourceServerModuleWebSecurityConfiguration method buildInternal.

private static OidcResourceServerModuleWebSecurityConfiguration buildInternal(OidcAuthenticationModuleType modelType, String prefixOfSequence) {
    OidcResourceServerModuleWebSecurityConfiguration configuration = new OidcResourceServerModuleWebSecurityConfiguration();
    build(configuration, modelType, prefixOfSequence);
    OidcResourceServerAuthenticationModuleType resourceServer = modelType.getResourceServer();
    if (resourceServer.getTrustingAsymmetricCertificate() != null || resourceServer.getKeyStoreTrustingAsymmetricKey() != null) {
        NimbusJwtDecoder.PublicKeyJwtDecoderBuilder builder;
        if (resourceServer.getKeyStoreTrustingAsymmetricKey() != null) {
            builder = initializePublicKeyDecoderFromKeyStore(resourceServer.getKeyStoreTrustingAsymmetricKey());
        } else {
            builder = initializePublicKeyDecoderFromCertificate(resourceServer.getTrustingAsymmetricCertificate());
        }
        if (resourceServer.getTrustedAlgorithm() != null) {
            builder.signatureAlgorithm(SignatureAlgorithm.from(resourceServer.getTrustedAlgorithm()));
        }
        configuration.decoder = builder.build();
    } else if (resourceServer.getSingleSymmetricKey() != null) {
        try {
            byte[] key;
            String clearValue = protector.decryptString(resourceServer.getSingleSymmetricKey());
            if (Base64.isBase64(clearValue)) {
                boolean isBase64Url = clearValue.contains("-") || clearValue.contains("_");
                key = Base64Utility.decode(clearValue, isBase64Url);
            } else {
                key = protector.decryptString(resourceServer.getSingleSymmetricKey()).getBytes();
            }
            String algorithm = MacAlgorithm.HS256.getName();
            if (resourceServer.getTrustedAlgorithm() != null) {
                algorithm = resourceServer.getTrustedAlgorithm();
            }
            NimbusJwtDecoder.SecretKeyJwtDecoderBuilder builder = NimbusJwtDecoder.withSecretKey(new SecretKeySpec(key, algorithm));
            builder.macAlgorithm(MacAlgorithm.from(algorithm));
            configuration.decoder = builder.build();
        } catch (EncryptionException e) {
            throw new OAuth2AuthenticationException(new OAuth2Error("missing_key"), "Unable get single symmetric key", e);
        } catch (Base64Exception e) {
            e.printStackTrace();
        }
    } else if (resourceServer.getJwkSetUri() != null) {
        if (resourceServer.getTrustedAlgorithm() != null) {
            configuration.decoder = NimbusJwtDecoder.withJwkSetUri(resourceServer.getJwkSetUri()).jwsAlgorithm(SignatureAlgorithm.from(resourceServer.getTrustedAlgorithm())).build();
        } else {
            try {
                JWSKeySelector<SecurityContext> jwsKeySelector = JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(new URL(resourceServer.getJwkSetUri()));
                DefaultJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
                jwtProcessor.setJWSKeySelector(jwsKeySelector);
                configuration.decoder = new NimbusJwtDecoder(jwtProcessor);
            } catch (KeySourceException | MalformedURLException e) {
                e.printStackTrace();
            }
        }
    } else if (resourceServer.getIssuerUri() != null) {
        configuration.decoder = JwtDecoders.fromIssuerLocation(resourceServer.getIssuerUri());
    }
    return configuration;
}
Also used : MalformedURLException(java.net.MalformedURLException) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) URL(java.net.URL) DefaultJWTProcessor(com.nimbusds.jwt.proc.DefaultJWTProcessor) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Base64Exception(org.apache.cxf.common.util.Base64Exception) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) SecurityContext(com.nimbusds.jose.proc.SecurityContext) KeySourceException(com.nimbusds.jose.KeySourceException)

Example 24 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project jhipster-registry by jhipster.

the class AuthorizationHeaderUtil method refreshTokenClient.

private OAuth2AccessTokenResponse refreshTokenClient(OAuth2AuthorizedClient currentClient) {
    MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
    formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue());
    formParameters.add(OAuth2ParameterNames.REFRESH_TOKEN, currentClient.getRefreshToken().getTokenValue());
    formParameters.add(OAuth2ParameterNames.CLIENT_ID, currentClient.getClientRegistration().getClientId());
    RequestEntity requestEntity = RequestEntity.post(URI.create(currentClient.getClientRegistration().getProviderDetails().getTokenUri())).contentType(MediaType.APPLICATION_FORM_URLENCODED).body(formParameters);
    try {
        RestTemplate r = restTemplate(currentClient.getClientRegistration().getClientId(), currentClient.getClientRegistration().getClientSecret());
        ResponseEntity<OAuthIdpTokenResponseDTO> responseEntity = r.exchange(requestEntity, OAuthIdpTokenResponseDTO.class);
        return toOAuth2AccessTokenResponse(responseEntity.getBody());
    } catch (OAuth2AuthorizationException e) {
        log.error("Unable to refresh token", e);
        throw new OAuth2AuthenticationException(e.getError(), e);
    }
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RestTemplate(org.springframework.web.client.RestTemplate) RequestEntity(org.springframework.http.RequestEntity) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 25 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project jhipster-registry by jhipster.

the class UaaAuthorizationHeaderUtil method retrieveNewAccessToken.

private OAuth2AccessToken retrieveNewAccessToken(ClientRegistration clientRegistration) {
    MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
    formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
    RequestEntity requestEntity = RequestEntity.post(URI.create(clientRegistration.getProviderDetails().getTokenUri())).contentType(MediaType.APPLICATION_FORM_URLENCODED).body(formParameters);
    try {
        ResponseEntity<OAuth2AccessTokenResponse> responseEntity = this.uaaRestTemplate.exchange(requestEntity, OAuth2AccessTokenResponse.class);
        return Objects.requireNonNull(responseEntity.getBody()).getAccessToken();
    } catch (OAuth2AuthorizationException e) {
        log.error("Unable to get access token", e);
        throw new OAuth2AuthenticationException(e.getError(), e);
    }
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RequestEntity(org.springframework.http.RequestEntity) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Aggregations

OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)54 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)31 Test (org.junit.jupiter.api.Test)27 BearerTokenError (org.springframework.security.oauth2.server.resource.BearerTokenError)21 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)10 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)9 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)8 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)8 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)7 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)7 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)7 Map (java.util.Map)6 Authentication (org.springframework.security.core.Authentication)6 AuthenticationException (org.springframework.security.core.AuthenticationException)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)6 OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)6 Mono (reactor.core.publisher.Mono)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 Base64 (java.util.Base64)5