Search in sources :

Example 26 with OidcUser

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

the class DhisOidcUserService method loadUser.

@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
    ClientRegistration clientRegistration = userRequest.getClientRegistration();
    DhisOidcClientRegistration oidcClientRegistration = clientRegistrationRepository.getDhisOidcClientRegistration(clientRegistration.getRegistrationId());
    String mappingClaimKey = oidcClientRegistration.getMappingClaimKey();
    OidcUser oidcUser = super.loadUser(userRequest);
    OidcUserInfo userInfo = oidcUser.getUserInfo();
    Map<String, Object> attributes = oidcUser.getAttributes();
    Object claimValue = attributes.get(mappingClaimKey);
    if (claimValue == null && userInfo != null) {
        claimValue = userInfo.getClaim(mappingClaimKey);
    }
    if (log.isDebugEnabled()) {
        log.debug(String.format("Trying to look up DHIS2 user with OidcUser mapping mappingClaimKey='%s', claim value='%s'", mappingClaimKey, claimValue));
    }
    if (claimValue != null) {
        User user = userService.getUserByOpenId((String) claimValue);
        if (user != null) {
            return new DhisOidcUser(user, attributes, IdTokenClaimNames.SUB, oidcUser.getIdToken());
        }
    }
    String errorMessage = String.format("Failed to look up DHIS2 user with OidcUser mapping mappingClaimKey='%s', claim value='%s'", mappingClaimKey, claimValue);
    if (log.isDebugEnabled()) {
        log.debug(errorMessage);
    }
    OAuth2Error oauth2Error = new OAuth2Error("could_not_map_oidc_user_to_dhis2_user", errorMessage, null);
    throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) User(org.hisp.dhis.user.User) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OidcUserInfo(org.springframework.security.oauth2.core.oidc.OidcUserInfo) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser)

Example 27 with OidcUser

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

the class SecurityMockMvcRequestPostProcessorsOidcLoginTests method oidcLoginWhenNameSpecifiedThenUserHasName.

@Test
public void oidcLoginWhenNameSpecifiedThenUserHasName() throws Exception {
    OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"), OidcIdToken.withTokenValue("id-token").claim("custom-attribute", "test-subject").build(), "custom-attribute");
    this.mvc.perform(get("/id-token/custom-attribute").with(oidcLogin().oidcUser(oidcUser))).andExpect(content().string("test-subject"));
    this.mvc.perform(get("/name").with(oidcLogin().oidcUser(oidcUser))).andExpect(content().string("test-subject"));
    this.mvc.perform(get("/client-name").with(oidcLogin().oidcUser(oidcUser))).andExpect(content().string("test-subject"));
}
Also used : 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 28 with OidcUser

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

the class SecurityMockServerConfigurersOidcLoginTests method oidcLoginWhenOidcUserSpecifiedThenLastCalledTakesPrecedence.

// gh-7794
@Test
public void oidcLoginWhenOidcUserSpecifiedThenLastCalledTakesPrecedence() throws Exception {
    OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.createAuthorityList("SCOPE_read"), TestOidcIdTokens.idToken().build());
    this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin().idToken((i) -> i.subject("foo")).oidcUser(oidcUser)).get().uri("/token").exchange().expectStatus().isOk();
    OAuth2AuthenticationToken token = this.controller.token;
    assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "subject");
    this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin().oidcUser(oidcUser).idToken((i) -> i.subject("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) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) 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) GetMapping(org.springframework.web.bind.annotation.GetMapping) SecurityContextServerWebExchangeWebFilter(org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) TestOidcIdTokens(org.springframework.security.oauth2.core.oidc.TestOidcIdTokens) 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) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.jupiter.api.Test) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) ServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) 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 29 with OidcUser

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

the class SecurityMockServerConfigurersOidcLoginTests method oidcLoginWhenUsingDefaultsThenProducesDefaultAuthentication.

@Test
public void oidcLoginWhenUsingDefaultsThenProducesDefaultAuthentication() {
    this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin()).get().uri("/token").exchange().expectStatus().isOk();
    OAuth2AuthenticationToken token = this.controller.token;
    assertThat(token).isNotNull();
    assertThat(token.getAuthorizedClientRegistrationId()).isEqualTo("test");
    assertThat(token.getPrincipal()).isInstanceOf(OidcUser.class);
    assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "user");
    assertThat((Collection<GrantedAuthority>) token.getPrincipal().getAuthorities()).contains(new SimpleGrantedAuthority("SCOPE_read"));
    assertThat(((OidcUser) token.getPrincipal()).getIdToken().getTokenValue()).isEqualTo("id-token");
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) Collection(java.util.Collection) Test(org.junit.jupiter.api.Test)

Example 30 with OidcUser

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

the class OidcUserService method loadUser.

@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
    Assert.notNull(userRequest, "userRequest cannot be null");
    OidcUserInfo userInfo = null;
    if (this.shouldRetrieveUserInfo(userRequest)) {
        OAuth2User oauth2User = this.oauth2UserService.loadUser(userRequest);
        Map<String, Object> claims = getClaims(userRequest, oauth2User);
        userInfo = new OidcUserInfo(claims);
        // 1) The sub (subject) Claim MUST always be returned in the UserInfo Response
        if (userInfo.getSubject() == null) {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
        // the UserInfo Response values MUST NOT be used.
        if (!userInfo.getSubject().equals(userRequest.getIdToken().getSubject())) {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
    }
    Set<GrantedAuthority> authorities = new LinkedHashSet<>();
    authorities.add(new OidcUserAuthority(userRequest.getIdToken(), userInfo));
    OAuth2AccessToken token = userRequest.getAccessToken();
    for (String authority : token.getScopes()) {
        authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
    }
    return getUser(userRequest, userInfo, authorities);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OidcUserAuthority(org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OidcUserInfo(org.springframework.security.oauth2.core.oidc.OidcUserInfo) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

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