Search in sources :

Example 41 with OAuth2AuthenticationException

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

the class ReactiveOidcIdTokenDecoderFactory method buildDecoder.

private NimbusReactiveJwtDecoder buildDecoder(ClientRegistration clientRegistration) {
    JwsAlgorithm jwsAlgorithm = this.jwsAlgorithmResolver.apply(clientRegistration);
    if (jwsAlgorithm != null && SignatureAlgorithm.class.isAssignableFrom(jwsAlgorithm.getClass())) {
        // https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
        // 
        // 6. If the ID Token is received via direct communication between the Client
        // and the Token Endpoint (which it is in this flow),
        // the TLS server validation MAY be used to validate the issuer in place of
        // checking the token signature.
        // The Client MUST validate the signature of all other ID Tokens according to
        // JWS [JWS]
        // using the algorithm specified in the JWT alg Header Parameter.
        // The Client MUST use the keys provided by the Issuer.
        // 
        // 7. The alg value SHOULD be the default of RS256 or the algorithm sent by
        // the Client
        // in the id_token_signed_response_alg parameter during Registration.
        String jwkSetUri = clientRegistration.getProviderDetails().getJwkSetUri();
        if (!StringUtils.hasText(jwkSetUri)) {
            OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE, "Failed to find a Signature Verifier for Client Registration: '" + clientRegistration.getRegistrationId() + "'. Check to ensure you have configured the JwkSet URI.", null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
        return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).jwsAlgorithm((SignatureAlgorithm) jwsAlgorithm).build();
    }
    if (jwsAlgorithm != null && MacAlgorithm.class.isAssignableFrom(jwsAlgorithm.getClass())) {
        // https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
        // 
        // 8. If the JWT alg Header Parameter uses a MAC based algorithm such as
        // HS256, HS384, or HS512,
        // the octets of the UTF-8 representation of the client_secret
        // corresponding to the client_id contained in the aud (audience) Claim
        // are used as the key to validate the signature.
        // For MAC based algorithms, the behavior is unspecified if the aud is
        // multi-valued or
        // if an azp value is present that is different than the aud value.
        String clientSecret = clientRegistration.getClientSecret();
        if (!StringUtils.hasText(clientSecret)) {
            OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE, "Failed to find a Signature Verifier for Client Registration: '" + clientRegistration.getRegistrationId() + "'. Check to ensure you have configured the client secret.", null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
        SecretKeySpec secretKeySpec = new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8), JCA_ALGORITHM_MAPPINGS.get(jwsAlgorithm));
        return NimbusReactiveJwtDecoder.withSecretKey(secretKeySpec).macAlgorithm((MacAlgorithm) jwsAlgorithm).build();
    }
    OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE, "Failed to find a Signature Verifier for Client Registration: '" + clientRegistration.getRegistrationId() + "'. Check to ensure you have configured a valid JWS Algorithm: '" + jwsAlgorithm + "'", null);
    throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
Also used : JwsAlgorithm(org.springframework.security.oauth2.jose.jws.JwsAlgorithm) MacAlgorithm(org.springframework.security.oauth2.jose.jws.MacAlgorithm) SecretKeySpec(javax.crypto.spec.SecretKeySpec) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) SignatureAlgorithm(org.springframework.security.oauth2.jose.jws.SignatureAlgorithm) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 42 with OAuth2AuthenticationException

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

the class DefaultOAuth2UserService method loadUser.

@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
    Assert.notNull(userRequest, "userRequest cannot be null");
    if (!StringUtils.hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) {
        OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE, "Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
    if (!StringUtils.hasText(userNameAttributeName)) {
        OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE, "Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    RequestEntity<?> request = this.requestEntityConverter.convert(userRequest);
    ResponseEntity<Map<String, Object>> response = getResponse(userRequest, request);
    Map<String, Object> userAttributes = response.getBody();
    Set<GrantedAuthority> authorities = new LinkedHashSet<>();
    authorities.add(new OAuth2UserAuthority(userAttributes));
    OAuth2AccessToken token = userRequest.getAccessToken();
    for (String authority : token.getScopes()) {
        authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
    }
    return new DefaultOAuth2User(authorities, userAttributes, userNameAttributeName);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Map(java.util.Map)

Example 43 with OAuth2AuthenticationException

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

the class OidcUserService method loadUser.

@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
    Assert.notNull(userRequest, "userRequest cannot be null");
    OidcUserInfo userInfo = null;
    if (this.shouldRetrieveUserInfo(userRequest)) {
        OAuth2User oauth2User = this.oauth2UserService.loadUser(userRequest);
        Map<String, Object> claims = getClaims(userRequest, oauth2User);
        userInfo = new OidcUserInfo(claims);
        // 1) The sub (subject) Claim MUST always be returned in the UserInfo Response
        if (userInfo.getSubject() == null) {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
        // the UserInfo Response values MUST NOT be used.
        if (!userInfo.getSubject().equals(userRequest.getIdToken().getSubject())) {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
    }
    Set<GrantedAuthority> authorities = new LinkedHashSet<>();
    authorities.add(new OidcUserAuthority(userRequest.getIdToken(), userInfo));
    OAuth2AccessToken token = userRequest.getAccessToken();
    for (String authority : token.getScopes()) {
        authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
    }
    return getUser(userRequest, userInfo, authorities);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OidcUserAuthority(org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OidcUserInfo(org.springframework.security.oauth2.core.oidc.OidcUserInfo) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 44 with OAuth2AuthenticationException

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

the class BearerTokenAuthenticationEntryPointTests method commenceWhenInvalidRequestErrorThenStatus400AndHeaderWithError.

@Test
public void commenceWhenInvalidRequestErrorThenStatus400AndHeaderWithError() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST, null, null);
    this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
    assertThat(response.getStatus()).isEqualTo(400);
    assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer error=\"invalid_request\"");
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 45 with OAuth2AuthenticationException

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

the class BearerTokenAuthenticationEntryPointTests method commenceWhenInsufficientScopeErrorThenStatus403AndHeaderWithErrorAndScope.

@Test
public void commenceWhenInsufficientScopeErrorThenStatus403AndHeaderWithErrorAndScope() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN, null, null, "test.read test.write");
    this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
    assertThat(response.getStatus()).isEqualTo(403);
    assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer error=\"insufficient_scope\", scope=\"test.read test.write\"");
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

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