Search in sources :

Example 1 with OAuth2User

use of org.springframework.security.oauth2.core.user.OAuth2User 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 2 with OAuth2User

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

the class OAuth2LoginAuthenticationFilterTests method setUpAuthenticationResult.

private void setUpAuthenticationResult(ClientRegistration registration) {
    OAuth2User user = mock(OAuth2User.class);
    given(user.getName()).willReturn(this.principalName1);
    this.loginAuthentication = mock(OAuth2LoginAuthenticationToken.class);
    given(this.loginAuthentication.getPrincipal()).willReturn(user);
    given(this.loginAuthentication.getName()).willReturn(this.principalName1);
    given(this.loginAuthentication.getAuthorities()).willReturn(AuthorityUtils.createAuthorityList("ROLE_USER"));
    given(this.loginAuthentication.getClientRegistration()).willReturn(registration);
    given(this.loginAuthentication.getAuthorizationExchange()).willReturn(TestOAuth2AuthorizationExchanges.success());
    given(this.loginAuthentication.getAccessToken()).willReturn(mock(OAuth2AccessToken.class));
    given(this.loginAuthentication.getRefreshToken()).willReturn(mock(OAuth2RefreshToken.class));
    given(this.loginAuthentication.isAuthenticated()).willReturn(true);
    given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(this.loginAuthentication);
}
Also used : OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Authentication(org.springframework.security.core.Authentication) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)

Example 3 with OAuth2User

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

the class OAuth2LoginBeanDefinitionParserTests method requestWhenAuthorizationResponseValidThenAuthenticate.

@Test
public void requestWhenAuthorizationResponseValidThenAuthenticate() throws Exception {
    this.spring.configLocations(this.xml("MultiClientRegistration-WithCustomConfiguration")).autowire();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, "github-login");
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().attributes(attributes).build();
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())).willReturn(authorizationRequest);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    OAuth2User oauth2User = TestOAuth2Users.create();
    given(this.oauth2UserService.loadUser(any())).willReturn(oauth2User);
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("code", "code123");
    params.add("state", authorizationRequest.getState());
    // @formatter:off
    this.mvc.perform(get("/login/oauth2/code/github-login").params(params)).andExpect(status().is2xxSuccessful());
    // @formatter:on
    ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
    verify(this.authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), authenticationCaptor.capture());
    Authentication authentication = authenticationCaptor.getValue();
    assertThat(authentication.getPrincipal()).isInstanceOf(OAuth2User.class);
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 4 with OAuth2User

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

the class SecurityMockServerConfigurersOidcLoginTests method oidcUserWhenNameSpecifiedThenUserHasName.

@Test
public void oidcUserWhenNameSpecifiedThenUserHasName() throws Exception {
    OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"), OidcIdToken.withTokenValue("id-token").claim("custom-attribute", "test-subject").build(), "custom-attribute");
    this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oidcUser)).get().uri("/token").exchange().expectStatus().isOk();
    OAuth2AuthenticationToken token = this.controller.token;
    assertThat(token.getPrincipal().getName()).isEqualTo("test-subject");
    this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oidcUser)).get().uri("/client").exchange().expectStatus().isOk();
    OAuth2AuthorizedClient client = this.controller.authorizedClient;
    assertThat(client.getPrincipalName()).isEqualTo("test-subject");
}
Also used : OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) Test(org.junit.jupiter.api.Test)

Example 5 with OAuth2User

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

the class SecurityMockServerConfigurersOAuth2LoginTests method oauth2LoginWhenOAuth2UserSpecifiedThenLastCalledTakesPrecedence.

@Test
public void oauth2LoginWhenOAuth2UserSpecifiedThenLastCalledTakesPrecedence() throws Exception {
    OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("SCOPE_read"), Collections.singletonMap("sub", "subject"), "sub");
    this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().attributes((a) -> a.put("subject", "foo")).oauth2User(oauth2User)).get().uri("/token").exchange().expectStatus().isOk();
    OAuth2AuthenticationToken token = this.controller.token;
    assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "subject");
    this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User).attributes((a) -> a.put("sub", "bar"))).get().uri("/token").exchange().expectStatus().isOk();
    token = this.controller.token;
    assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "bar");
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Mock(org.mockito.Mock) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) GetMapping(org.springframework.web.bind.annotation.GetMapping) SecurityContextServerWebExchangeWebFilter(org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) HttpHeaders(org.springframework.http.HttpHeaders) Collection(java.util.Collection) MediaType(org.springframework.http.MediaType) OAuth2AuthorizedClientArgumentResolver(org.springframework.security.oauth2.client.web.reactive.result.method.annotation.OAuth2AuthorizedClientArgumentResolver) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) RestController(org.springframework.web.bind.annotation.RestController) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.jupiter.api.Test) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) ServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)44 Test (org.junit.jupiter.api.Test)37 HashMap (java.util.HashMap)22 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)16 DefaultOAuth2User (org.springframework.security.oauth2.core.user.DefaultOAuth2User)15 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)14 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)13 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)13 GrantedAuthority (org.springframework.security.core.GrantedAuthority)12 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)12 Map (java.util.Map)10 OAuth2AuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken)10 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)9 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)9 Authentication (org.springframework.security.core.Authentication)8 AuthorityUtils (org.springframework.security.core.authority.AuthorityUtils)8 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)8 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)7 BeforeEach (org.junit.jupiter.api.BeforeEach)7 Mockito.mock (org.mockito.Mockito.mock)7