Search in sources :

Example 6 with OidcUser

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

the class OidcUserService method getUser.

private OidcUser getUser(OidcUserRequest userRequest, OidcUserInfo userInfo, Set<GrantedAuthority> authorities) {
    ProviderDetails providerDetails = userRequest.getClientRegistration().getProviderDetails();
    String userNameAttributeName = providerDetails.getUserInfoEndpoint().getUserNameAttributeName();
    if (StringUtils.hasText(userNameAttributeName)) {
        return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo, userNameAttributeName);
    }
    return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo);
}
Also used : ProviderDetails(org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser)

Example 7 with OidcUser

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

the class OidcClientInitiatedLogoutSuccessHandler method determineTargetUrl.

@Override
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String targetUrl = null;
    if (authentication instanceof OAuth2AuthenticationToken && authentication.getPrincipal() instanceof OidcUser) {
        String registrationId = ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId();
        ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
        URI endSessionEndpoint = this.endSessionEndpoint(clientRegistration);
        if (endSessionEndpoint != null) {
            String idToken = idToken(authentication);
            String postLogoutRedirectUri = postLogoutRedirectUri(request);
            targetUrl = endpointUri(endSessionEndpoint, idToken, postLogoutRedirectUri);
        }
    }
    return (targetUrl != null) ? targetUrl : super.determineTargetUrl(request, response);
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) URI(java.net.URI) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser)

Example 8 with OidcUser

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

the class SecurityMockMvcRequestPostProcessorsOidcLoginTests method oidcLoginWhenOidcUserSpecifiedThenLastCalledTakesPrecedence.

// gh-7794
@Test
public void oidcLoginWhenOidcUserSpecifiedThenLastCalledTakesPrecedence() throws Exception {
    OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.createAuthorityList("SCOPE_read"), TestOidcIdTokens.idToken().build());
    this.mvc.perform(get("/id-token/sub").with(oidcLogin().idToken((i) -> i.subject("foo")).oidcUser(oidcUser))).andExpect(status().isOk()).andExpect(content().string("subject"));
    this.mvc.perform(get("/id-token/sub").with(oidcLogin().oidcUser(oidcUser).idToken((i) -> i.subject("bar")))).andExpect(content().string("bar"));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) PathVariable(org.springframework.web.bind.annotation.PathVariable) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) 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) TestSecurityContextHolder(org.springframework.security.test.context.TestSecurityContextHolder) MockMvcResultMatchers.status(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status) MockMvcBuilders(org.springframework.test.web.servlet.setup.MockMvcBuilders) GetMapping(org.springframework.web.bind.annotation.GetMapping) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) WebAppConfiguration(org.springframework.test.context.web.WebAppConfiguration) TestOidcIdTokens(org.springframework.security.oauth2.core.oidc.TestOidcIdTokens) 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) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) 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) AfterEach(org.junit.jupiter.api.AfterEach) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) EnableWebSecurity(org.springframework.security.config.annotation.web.configuration.EnableWebSecurity) ContextConfiguration(org.springframework.test.context.ContextConfiguration) AuthenticationPrincipal(org.springframework.security.core.annotation.AuthenticationPrincipal) MockMvcRequestBuilders.get(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get) Bean(org.springframework.context.annotation.Bean) SecurityMockMvcRequestPostProcessors.oidcLogin(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oidcLogin) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) Mockito.mock(org.mockito.Mockito.mock) 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 9 with OidcUser

use of org.springframework.security.oauth2.core.oidc.user.OidcUser 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 10 with OidcUser

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

the class OidcAuthorizationCodeAuthenticationProviderTests method authenticateWhenLoginSuccessThenReturnAuthentication.

@Test
public void authenticateWhenLoginSuccessThenReturnAuthentication() {
    Map<String, Object> claims = new HashMap<>();
    claims.put(IdTokenClaimNames.ISS, "https://provider.com");
    claims.put(IdTokenClaimNames.SUB, "subject1");
    claims.put(IdTokenClaimNames.AUD, Arrays.asList("client1", "client2"));
    claims.put(IdTokenClaimNames.AZP, "client1");
    claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
    this.setUpIdToken(claims);
    OidcUser principal = mock(OidcUser.class);
    List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
    given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
    given(this.userService.loadUser(any())).willReturn(principal);
    OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
    assertThat(authentication.isAuthenticated()).isTrue();
    assertThat(authentication.getPrincipal()).isEqualTo(principal);
    assertThat(authentication.getCredentials()).isEqualTo("");
    assertThat(authentication.getAuthorities()).isEqualTo(authorities);
    assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
    assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
    assertThat(authentication.getAccessToken()).isEqualTo(this.accessTokenResponse.getAccessToken());
    assertThat(authentication.getRefreshToken()).isEqualTo(this.accessTokenResponse.getRefreshToken());
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Jwt(org.springframework.security.oauth2.jwt.Jwt) StringKeyGenerator(org.springframework.security.crypto.keygen.StringKeyGenerator) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Set(java.util.Set) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) Instant(java.time.Instant) 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) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IdTokenClaimNames(org.springframework.security.oauth2.core.oidc.IdTokenClaimNames) TestOAuth2AuthorizationRequests(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests) 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) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) LinkedHashSet(java.util.LinkedHashSet) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) OAuth2UserService(org.springframework.security.oauth2.client.userinfo.OAuth2UserService) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) TestOAuth2AuthorizationResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses) 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) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) HashMap(java.util.HashMap) GrantedAuthority(org.springframework.security.core.GrantedAuthority) List(java.util.List) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) Test(org.junit.jupiter.api.Test)

Aggregations

OidcUser (org.springframework.security.oauth2.core.oidc.user.OidcUser)30 Test (org.junit.jupiter.api.Test)24 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)14 GrantedAuthority (org.springframework.security.core.GrantedAuthority)8 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)8 OAuth2AuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken)8 DefaultOidcUser (org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser)8 OidcUserRequest (org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest)7 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)6 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)6 BeforeEach (org.junit.jupiter.api.BeforeEach)5 AuthorityUtils (org.springframework.security.core.authority.AuthorityUtils)5 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)5 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)5 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)5 HashMap (java.util.HashMap)4 LinkedHashSet (java.util.LinkedHashSet)4 List (java.util.List)4 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)4 GrantedAuthoritiesMapper (org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper)4