Search in sources :

Example 1 with OAuth2LoginAuthenticationToken

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

the class OidcAuthorizationCodeAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2LoginAuthenticationToken authorizationCodeAuthentication = (OAuth2LoginAuthenticationToken) authentication;
    // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
    if (!authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains(OidcScopes.OPENID)) {
        // and let OAuth2LoginAuthenticationProvider handle it instead
        return null;
    }
    OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest();
    OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationResponse();
    if (authorizationResponse.statusError()) {
        throw new OAuth2AuthenticationException(authorizationResponse.getError(), authorizationResponse.getError().toString());
    }
    if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    OAuth2AccessTokenResponse accessTokenResponse = getResponse(authorizationCodeAuthentication);
    ClientRegistration clientRegistration = authorizationCodeAuthentication.getClientRegistration();
    Map<String, Object> additionalParameters = accessTokenResponse.getAdditionalParameters();
    if (!additionalParameters.containsKey(OidcParameterNames.ID_TOKEN)) {
        OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, "Missing (required) ID Token in Token Response for Client Registration: " + clientRegistration.getRegistrationId(), null);
        throw new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString());
    }
    OidcIdToken idToken = createOidcToken(clientRegistration, accessTokenResponse);
    validateNonce(authorizationRequest, idToken);
    OidcUser oidcUser = this.userService.loadUser(new OidcUserRequest(clientRegistration, accessTokenResponse.getAccessToken(), idToken, additionalParameters));
    Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper.mapAuthorities(oidcUser.getAuthorities());
    OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange(), oidcUser, mappedAuthorities, accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken());
    authenticationResult.setDetails(authorizationCodeAuthentication.getDetails());
    return authenticationResult;
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)

Example 2 with OAuth2LoginAuthenticationToken

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

the class OAuth2LoginAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2LoginAuthenticationToken loginAuthenticationToken = (OAuth2LoginAuthenticationToken) authentication;
    // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
    if (loginAuthenticationToken.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
        // and let OidcAuthorizationCodeAuthenticationProvider handle it instead
        return null;
    }
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthenticationToken;
    try {
        authorizationCodeAuthenticationToken = (OAuth2AuthorizationCodeAuthenticationToken) this.authorizationCodeAuthenticationProvider.authenticate(new OAuth2AuthorizationCodeAuthenticationToken(loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange()));
    } catch (OAuth2AuthorizationException ex) {
        OAuth2Error oauth2Error = ex.getError();
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
    }
    OAuth2AccessToken accessToken = authorizationCodeAuthenticationToken.getAccessToken();
    Map<String, Object> additionalParameters = authorizationCodeAuthenticationToken.getAdditionalParameters();
    OAuth2User oauth2User = this.userService.loadUser(new OAuth2UserRequest(loginAuthenticationToken.getClientRegistration(), accessToken, additionalParameters));
    Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper.mapAuthorities(oauth2User.getAuthorities());
    OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange(), oauth2User, mappedAuthorities, accessToken, authorizationCodeAuthenticationToken.getRefreshToken());
    authenticationResult.setDetails(loginAuthenticationToken.getDetails());
    return authenticationResult;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 3 with OAuth2LoginAuthenticationToken

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

the class OAuth2LoginAuthenticationFilterTests method doFilterWhenAuthorizationResponseHasNonDefaultPortThenRedirectUriMatchingIncludesPort.

// gh-5890
@Test
public void doFilterWhenAuthorizationResponseHasNonDefaultPortThenRedirectUriMatchingIncludesPort() throws Exception {
    String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
    String state = "state";
    MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
    request.setScheme("https");
    request.setServerName("example.com");
    request.setServerPort(9090);
    request.setServletPath(requestUri);
    request.addParameter(OAuth2ParameterNames.CODE, "code");
    request.addParameter(OAuth2ParameterNames.STATE, "state");
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    this.setUpAuthorizationRequest(request, response, this.registration2, state);
    this.setUpAuthenticationResult(this.registration2);
    this.filter.doFilter(request, response, filterChain);
    ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
    verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture());
    OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor.getValue();
    OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange().getAuthorizationRequest();
    OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange().getAuthorizationResponse();
    String expectedRedirectUri = "https://example.com:9090/login/oauth2/code/registration-id-2";
    assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri);
    assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Authentication(org.springframework.security.core.Authentication) FilterChain(jakarta.servlet.FilterChain) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 4 with OAuth2LoginAuthenticationToken

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

the class OAuth2LoginAuthenticationWebFilterTests method loginToken.

private OAuth2LoginAuthenticationToken loginToken() {
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofDays(1)), Collections.singleton("user"));
    DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
    ClientRegistration clientRegistration = this.registration.build();
    // @formatter:off
    OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode().state("state").clientId(clientRegistration.getClientId()).authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri()).redirectUri(clientRegistration.getRedirectUri()).scopes(clientRegistration.getScopes()).build();
    OAuth2AuthorizationResponse authorizationResponse = this.authorizationResponseBldr.redirectUri(clientRegistration.getRedirectUri()).build();
    // @formatter:on
    OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse);
    return new OAuth2LoginAuthenticationToken(clientRegistration, authorizationExchange, user, user.getAuthorities(), accessToken);
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)

Example 5 with OAuth2LoginAuthenticationToken

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

the class OAuth2LoginAuthenticationFilterTests method doFilterWhenAuthorizationResponseHasDefaultPort80ThenRedirectUriMatchingExcludesPort.

// gh-5890
@Test
public void doFilterWhenAuthorizationResponseHasDefaultPort80ThenRedirectUriMatchingExcludesPort() throws Exception {
    String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
    String state = "state";
    MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
    request.setScheme("http");
    request.setServerName("localhost");
    request.setServerPort(80);
    request.setServletPath(requestUri);
    request.addParameter(OAuth2ParameterNames.CODE, "code");
    request.addParameter(OAuth2ParameterNames.STATE, "state");
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    this.setUpAuthorizationRequest(request, response, this.registration2, state);
    this.setUpAuthenticationResult(this.registration2);
    this.filter.doFilter(request, response, filterChain);
    ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
    verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture());
    OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor.getValue();
    OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange().getAuthorizationRequest();
    OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange().getAuthorizationResponse();
    String expectedRedirectUri = "http://localhost/login/oauth2/code/registration-id-2";
    assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri);
    assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Authentication(org.springframework.security.core.Authentication) FilterChain(jakarta.servlet.FilterChain) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)29 Test (org.junit.jupiter.api.Test)25 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)23 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)21 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)20 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)16 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)15 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)15 Authentication (org.springframework.security.core.Authentication)13 HashMap (java.util.HashMap)12 Map (java.util.Map)12 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)11 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)11 BDDMockito.given (org.mockito.BDDMockito.given)11 Mockito.mock (org.mockito.Mockito.mock)11 Answer (org.mockito.stubbing.Answer)11 AuthorityUtils (org.springframework.security.core.authority.AuthorityUtils)11 TestClientRegistrations (org.springframework.security.oauth2.client.registration.TestClientRegistrations)11