Search in sources :

Example 11 with DefaultOAuth2User

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenDefaultOAuth2AuthorizedClientFalseThenEmpty.

@Test
public void filterWhenDefaultOAuth2AuthorizedClientFalseThenEmpty() {
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
    OAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
    OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, user.getAuthorities(), "client-id");
    // @formatter:off
    this.function.filter(request, this.exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)).block();
    // @formatter:on
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    verifyZeroInteractions(this.clientRegistrationRepository, this.authorizedClientRepository);
}
Also used : 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) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 12 with DefaultOAuth2User

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenClientRegistrationIdFromAuthenticationThenAuthorizedClientResolved.

@Test
public void filterWhenClientRegistrationIdFromAuthenticationThenAuthorizedClientResolved() {
    this.function.setDefaultOAuth2AuthorizedClient(true);
    OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken);
    given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).willReturn(Mono.just(authorizedClient));
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
    OAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
    OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, user.getAuthorities(), "client-id");
    this.function.filter(request, this.exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)).subscriberContext(serverWebExchange()).block();
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    ClientRequest request0 = requests.get(0);
    assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
    assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
    assertThat(request0.method()).isEqualTo(HttpMethod.GET);
    assertThat(getBody(request0)).isEmpty();
}
Also used : DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 13 with DefaultOAuth2User

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

the class SecurityMockMvcRequestPostProcessorsOAuth2LoginTests method oauth2LoginWhenOAuth2UserSpecifiedThenLastCalledTakesPrecedence.

@Test
public void oauth2LoginWhenOAuth2UserSpecifiedThenLastCalledTakesPrecedence() throws Exception {
    OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("SCOPE_read"), Collections.singletonMap("username", "user"), "username");
    this.mvc.perform(get("/attributes/sub").with(oauth2Login().attributes((a) -> a.put("sub", "bar")).oauth2User(oauth2User))).andExpect(status().isOk()).andExpect(content().string("no-attribute"));
    this.mvc.perform(get("/attributes/sub").with(oauth2Login().oauth2User(oauth2User).attributes((a) -> a.put("sub", "bar")))).andExpect(content().string("bar"));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) PathVariable(org.springframework.web.bind.annotation.PathVariable) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) SecurityMockMvcRequestPostProcessors.oauth2Login(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oauth2Login) Autowired(org.springframework.beans.factory.annotation.Autowired) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) HttpSecurity(org.springframework.security.config.annotation.web.builders.HttpSecurity) MockMvcResultMatchers.content(org.springframework.test.web.servlet.result.MockMvcResultMatchers.content) MockMvc(org.springframework.test.web.servlet.MockMvc) WebSecurityConfigurerAdapter(org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) MockMvcResultMatchers.status(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) MockMvcBuilders(org.springframework.test.web.servlet.setup.MockMvcBuilders) GetMapping(org.springframework.web.bind.annotation.GetMapping) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) WebAppConfiguration(org.springframework.test.context.web.WebAppConfiguration) SpringExtension(org.springframework.test.context.junit.jupiter.SpringExtension) Collection(java.util.Collection) WebApplicationContext(org.springframework.web.context.WebApplicationContext) EnableWebMvc(org.springframework.web.servlet.config.annotation.EnableWebMvc) Collectors(java.util.stream.Collectors) 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) SecurityMockMvcConfigurers.springSecurity(org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity) List(java.util.List) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) EnableWebSecurity(org.springframework.security.config.annotation.web.configuration.EnableWebSecurity) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) ContextConfiguration(org.springframework.test.context.ContextConfiguration) AuthenticationPrincipal(org.springframework.security.core.annotation.AuthenticationPrincipal) MockMvcRequestBuilders.get(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get) Optional(java.util.Optional) Bean(org.springframework.context.annotation.Bean) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) Mockito.mock(org.mockito.Mockito.mock) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) Test(org.junit.jupiter.api.Test)

Example 14 with DefaultOAuth2User

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

the class SecurityMockServerConfigurersOAuth2LoginTests method oauth2LoginWhenNameSpecifiedThenUserHasName.

@Test
public void oauth2LoginWhenNameSpecifiedThenUserHasName() throws Exception {
    OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"), Collections.singletonMap("custom-attribute", "test-subject"), "custom-attribute");
    this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User)).get().uri("/token").exchange().expectStatus().isOk();
    OAuth2AuthenticationToken token = this.controller.token;
    assertThat(token.getPrincipal().getName()).isEqualTo("test-subject");
    this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User)).get().uri("/client").exchange().expectStatus().isOk();
    OAuth2AuthorizedClient client = this.controller.authorizedClient;
    assertThat(client.getPrincipalName()).isEqualTo("test-subject");
}
Also used : 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) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Test(org.junit.jupiter.api.Test)

Example 15 with DefaultOAuth2User

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

the class DefaultReactiveOAuth2UserService method loadUser.

@Override
public Mono<OAuth2User> loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
    return Mono.defer(() -> {
        Assert.notNull(userRequest, "userRequest cannot be null");
        String userInfoUri = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri();
        if (!StringUtils.hasText(userInfoUri)) {
            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());
        }
        AuthenticationMethod authenticationMethod = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod();
        WebClient.RequestHeadersSpec<?> requestHeadersSpec = getRequestHeaderSpec(userRequest, userInfoUri, authenticationMethod);
        // @formatter:off
        Mono<Map<String, Object>> userAttributes = requestHeadersSpec.retrieve().onStatus(HttpStatus::isError, (response) -> parse(response).map((userInfoErrorResponse) -> {
            String description = userInfoErrorResponse.getErrorObject().getDescription();
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, description, null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        })).bodyToMono(DefaultReactiveOAuth2UserService.STRING_OBJECT_MAP);
        return userAttributes.map((attrs) -> {
            GrantedAuthority authority = new OAuth2UserAuthority(attrs);
            Set<GrantedAuthority> authorities = new HashSet<>();
            authorities.add(authority);
            OAuth2AccessToken token = userRequest.getAccessToken();
            for (String scope : token.getScopes()) {
                authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope));
            }
            return new DefaultOAuth2User(authorities, attrs, userNameAttributeName);
        }).onErrorMap((ex) -> (ex instanceof UnsupportedMediaTypeException || ex.getCause() instanceof UnsupportedMediaTypeException), (ex) -> {
            String contentType = (ex instanceof UnsupportedMediaTypeException) ? ((UnsupportedMediaTypeException) ex).getContentType().toString() : ((UnsupportedMediaTypeException) ex.getCause()).getContentType().toString();
            String errorMessage = "An error occurred while attempting to retrieve the UserInfo Resource from '" + userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri() + "': response contains invalid content type '" + contentType + "'. " + "The UserInfo Response should return a JSON object (content type 'application/json') " + "that contains a collection of name and value pairs of the claims about the authenticated End-User. " + "Please ensure the UserInfo Uri in UserInfoEndpoint for Client Registration '" + userRequest.getClientRegistration().getRegistrationId() + "' conforms to the UserInfo Endpoint, " + "as defined in OpenID Connect 1.0: 'https://openid.net/specs/openid-connect-core-1_0.html#UserInfo'";
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, errorMessage, null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
        }).onErrorMap((ex) -> {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, "An error occurred reading the UserInfo response: " + ex.getMessage(), null);
            return new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
        });
    });
// @formatter:on
}
Also used : UnsupportedMediaTypeException(org.springframework.web.reactive.function.UnsupportedMediaTypeException) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) WebClient(org.springframework.web.reactive.function.client.WebClient) HashSet(java.util.HashSet) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) Map(java.util.Map) UserInfoErrorResponse(com.nimbusds.openid.connect.sdk.UserInfoErrorResponse) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) HttpHeaders(org.springframework.http.HttpHeaders) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) MediaType(org.springframework.http.MediaType) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Set(java.util.Set) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) Mono(reactor.core.publisher.Mono) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpStatus(org.springframework.http.HttpStatus) AuthenticationMethod(org.springframework.security.oauth2.core.AuthenticationMethod) JSONObject(net.minidev.json.JSONObject) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) AuthenticationMethod(org.springframework.security.oauth2.core.AuthenticationMethod) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) WebClient(org.springframework.web.reactive.function.client.WebClient) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UnsupportedMediaTypeException(org.springframework.web.reactive.function.UnsupportedMediaTypeException) 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) HashSet(java.util.HashSet)

Aggregations

DefaultOAuth2User (org.springframework.security.oauth2.core.user.DefaultOAuth2User)20 Test (org.junit.jupiter.api.Test)15 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)14 HashMap (java.util.HashMap)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)6 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)5 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)5 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)5 OAuth2AuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken)4 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)4 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)4 Collections (java.util.Collections)3 Map (java.util.Map)3 BeforeEach (org.junit.jupiter.api.BeforeEach)3 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)3 RegisteredOAuth2AuthorizedClient (org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient)3 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)3 Collection (java.util.Collection)2 HashSet (java.util.HashSet)2 List (java.util.List)2