Search in sources :

Example 26 with OAuth2AuthorizationCodeAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken in project spring-security by spring-projects.

the class OAuth2LoginReactiveAuthenticationManager method onSuccess.

private Mono<OAuth2LoginAuthenticationToken> onSuccess(OAuth2AuthorizationCodeAuthenticationToken authentication) {
    OAuth2AccessToken accessToken = authentication.getAccessToken();
    Map<String, Object> additionalParameters = authentication.getAdditionalParameters();
    OAuth2UserRequest userRequest = new OAuth2UserRequest(authentication.getClientRegistration(), accessToken, additionalParameters);
    return this.userService.loadUser(userRequest).map((oauth2User) -> {
        Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper.mapAuthorities(oauth2User.getAuthorities());
        OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(authentication.getClientRegistration(), authentication.getAuthorizationExchange(), oauth2User, mappedAuthorities, accessToken, authentication.getRefreshToken());
        return authenticationResult;
    });
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest)

Example 27 with OAuth2AuthorizationCodeAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken in project spring-security by spring-projects.

the class OAuth2AuthorizationCodeAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
    OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationResponse();
    if (authorizationResponse.statusError()) {
        throw new OAuth2AuthorizationException(authorizationResponse.getError());
    }
    OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest();
    if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange()));
    OAuth2AuthorizationCodeAuthenticationToken authenticationResult = new OAuth2AuthorizationCodeAuthenticationToken(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange(), accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken(), accessTokenResponse.getAdditionalParameters());
    authenticationResult.setDetails(authorizationCodeAuthentication.getDetails());
    return authenticationResult;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Example 28 with OAuth2AuthorizationCodeAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken in project spring-security by spring-projects.

the class OidcAuthorizationCodeReactiveAuthenticationManagerTests method authenticationWhenRefreshTokenThenRefreshTokenInAuthorizedClient.

@Test
public void authenticationWhenRefreshTokenThenRefreshTokenInAuthorizedClient() {
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue())).refreshToken("refresh-token").build();
    // @formatter:on
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
    Map<String, Object> claims = new HashMap<>();
    claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
    claims.put(IdTokenClaimNames.SUB, "rob");
    claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id"));
    claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
    Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
    given(this.userService.loadUser(any())).willReturn(Mono.just(user));
    given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
    this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
    OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(authorizationCodeAuthentication).block();
    assertThat(result.getPrincipal()).isEqualTo(user);
    assertThat(result.getAuthorities()).containsOnlyElementsOf(user.getAuthorities());
    assertThat(result.isAuthenticated()).isTrue();
    assertThat(result.getRefreshToken().getTokenValue()).isNotNull();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Jwt(org.springframework.security.oauth2.jwt.Jwt) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) StringKeyGenerator(org.springframework.security.crypto.keygen.StringKeyGenerator) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.jupiter.api.Test) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) Base64(java.util.Base64) List(java.util.List) Base64StringKeyGenerator(org.springframework.security.crypto.keygen.Base64StringKeyGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Authentication(org.springframework.security.core.Authentication) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Mock(org.mockito.Mock) IdTokenClaimNames(org.springframework.security.oauth2.core.oidc.IdTokenClaimNames) OidcParameterNames(org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames) HashMap(java.util.HashMap) Answer(org.mockito.stubbing.Answer) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ReactiveOAuth2UserService(org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) TestOidcIdTokens(org.springframework.security.oauth2.core.oidc.TestOidcIdTokens) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Mono(reactor.core.publisher.Mono) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) JwtException(org.springframework.security.oauth2.jwt.JwtException) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) HashMap(java.util.HashMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 29 with OAuth2AuthorizationCodeAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken in project spring-security by spring-projects.

the class OidcAuthorizationCodeReactiveAuthenticationManagerTests method authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities.

@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
    ClientRegistration clientRegistration = this.registration.build();
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue())).build();
    // @formatter:on
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
    Map<String, Object> claims = new HashMap<>();
    claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
    claims.put(IdTokenClaimNames.SUB, "rob");
    claims.put(IdTokenClaimNames.AUD, Collections.singletonList(clientRegistration.getClientId()));
    claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
    Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
    ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
    given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
    List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER");
    GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
    given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
    given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
    this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
    this.manager.setAuthoritiesMapper(authoritiesMapper);
    Authentication result = this.manager.authenticate(authorizationCodeAuthentication).block();
    assertThat(result.getAuthorities()).isEqualTo(mappedAuthorities);
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Jwt(org.springframework.security.oauth2.jwt.Jwt) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) StringKeyGenerator(org.springframework.security.crypto.keygen.StringKeyGenerator) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.jupiter.api.Test) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) Base64(java.util.Base64) List(java.util.List) Base64StringKeyGenerator(org.springframework.security.crypto.keygen.Base64StringKeyGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Authentication(org.springframework.security.core.Authentication) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Mock(org.mockito.Mock) IdTokenClaimNames(org.springframework.security.oauth2.core.oidc.IdTokenClaimNames) OidcParameterNames(org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames) HashMap(java.util.HashMap) Answer(org.mockito.stubbing.Answer) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) ReactiveOAuth2UserService(org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) TestOidcIdTokens(org.springframework.security.oauth2.core.oidc.TestOidcIdTokens) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Mono(reactor.core.publisher.Mono) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) JwtException(org.springframework.security.oauth2.jwt.JwtException) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) HashMap(java.util.HashMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Authentication(org.springframework.security.core.Authentication) List(java.util.List) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) Test(org.junit.jupiter.api.Test)

Example 30 with OAuth2AuthorizationCodeAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken in project spring-security by spring-projects.

the class OidcAuthorizationCodeReactiveAuthenticationManagerTests method loginToken.

private OAuth2AuthorizationCodeAuthenticationToken loginToken() {
    ClientRegistration clientRegistration = this.registration.build();
    Map<String, Object> attributes = new HashMap<>();
    Map<String, Object> additionalParameters = new HashMap<>();
    try {
        String nonce = this.secureKeyGenerator.generateKey();
        this.nonceHash = OidcAuthorizationCodeReactiveAuthenticationManager.createHash(nonce);
        attributes.put(OidcParameterNames.NONCE, nonce);
        additionalParameters.put(OidcParameterNames.NONCE, this.nonceHash);
    } catch (NoSuchAlgorithmException ex) {
    }
    // @formatter:off
    OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode().state("state").clientId(clientRegistration.getClientId()).authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri()).redirectUri(clientRegistration.getRedirectUri()).scopes(clientRegistration.getScopes()).additionalParameters(additionalParameters).attributes(attributes).build();
    OAuth2AuthorizationResponse authorizationResponse = this.authorizationResponseBldr.redirectUri(clientRegistration.getRedirectUri()).build();
    // @formatter:on
    OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse);
    return new OAuth2AuthorizationCodeAuthenticationToken(clientRegistration, authorizationExchange);
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) HashMap(java.util.HashMap) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Aggregations

OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)23 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)22 OAuth2AuthorizationCodeAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken)19 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)19 Test (org.junit.jupiter.api.Test)16 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)16 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)16 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)13 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)13 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)12 Authentication (org.springframework.security.core.Authentication)11 Mono (reactor.core.publisher.Mono)11 HashMap (java.util.HashMap)10 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)9 Map (java.util.Map)9 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)9 Base64 (java.util.Base64)8 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)8 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)8 BDDMockito.given (org.mockito.BDDMockito.given)8