Search in sources :

Example 86 with OAuth2AuthorizedClient

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

the class AuthenticatedPrincipalOAuth2AuthorizedClientRepositoryTests method saveAuthorizedClientWhenAnonymousPrincipalThenSaveToAnonymousRepository.

@Test
public void saveAuthorizedClientWhenAnonymousPrincipalThenSaveToAnonymousRepository() {
    Authentication authentication = this.createAnonymousPrincipal();
    OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
    this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authentication, this.request, this.response);
    verify(this.anonymousAuthorizedClientRepository).saveAuthorizedClient(authorizedClient, authentication, this.request, this.response);
}
Also used : Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Test(org.junit.jupiter.api.Test)

Example 87 with OAuth2AuthorizedClient

use of org.springframework.security.oauth2.client.OAuth2AuthorizedClient in project books by aidanwhiteley.

the class Oauth2AuthenticationUtils method getAuthenticationProvider.

public User.AuthenticationProvider getAuthenticationProvider(OAuth2AuthenticationToken auth) {
    OAuth2AuthorizedClient authorizedClient = this.getAuthorizedClient(auth);
    String clientId = authorizedClient.getClientRegistration().getClientId();
    if (clientId.equals(googleClientClientId)) {
        return GOOGLE;
    } else if (clientId.equals(facebookClientClientId)) {
        return FACEBOOK;
    } else {
        LOGGER.error("Unknown clientId specified of {} so cant determine authentication provider.", clientId);
        throw new IllegalArgumentException("Uknown client id specified");
    }
}
Also used : OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient)

Example 88 with OAuth2AuthorizedClient

use of org.springframework.security.oauth2.client.OAuth2AuthorizedClient in project books by aidanwhiteley.

the class Oauth2AuthenticationUtils method getUserIfExists.

public Optional<User> getUserIfExists(OAuth2AuthenticationToken authentication) {
    OAuth2AuthorizedClient authorizedClient = this.getAuthorizedClient(authentication);
    String authenticationProviderId = authorizedClient.getPrincipalName();
    List<User> users = userRepository.findAllByAuthenticationServiceIdAndAuthProvider(authenticationProviderId, this.getAuthenticationProvider(authentication).toString());
    User user;
    switch(users.size()) {
        case 0:
            user = null;
            break;
        case 1:
            user = users.get(0);
            break;
        default:
            LOGGER.error("More than one user found for Authentication: {}", authentication);
            throw new IllegalStateException("More that one user found for a given Authentication");
    }
    return Optional.ofNullable(user);
}
Also used : User(com.aidanwhiteley.books.domain.User) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient)

Example 89 with OAuth2AuthorizedClient

use of org.springframework.security.oauth2.client.OAuth2AuthorizedClient in project books by aidanwhiteley.

the class UserServiceTest method configureOauth.

private void configureOauth(String clientId, String name) {
    Map<String, Object> details = new LinkedHashMap<>();
    details.put("name", name);
    details.put(name, name);
    Set<GrantedAuthority> authorities = new HashSet<>();
    authorities.add(new SimpleGrantedAuthority("USER"));
    OAuth2User oauth2User = new DefaultOAuth2User(authorities, details, name);
    when(oauthToken.getName()).thenReturn(DUMMY);
    when(oauthToken.getAuthorizedClientRegistrationId()).thenReturn(DUMMY);
    when(oauthToken.getPrincipal()).thenReturn(oauth2User);
    OAuth2AuthorizedClient client = Mockito.mock(OAuth2AuthorizedClient.class);
    ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(DUMMY);
    builder.clientId(clientId).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).clientSecret(DUMMY).redirectUriTemplate(DUMMY).scope(DUMMY).authorizationUri(DUMMY).tokenUri(DUMMY).clientName(DUMMY);
    ClientRegistration clientReg = builder.build();
    when(client.getClientRegistration()).thenReturn(clientReg);
    when(authorisedClientService.loadAuthorizedClient(any(String.class), any(String.class))).thenReturn(client);
}
Also used : DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) LinkedHashMap(java.util.LinkedHashMap) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) HashSet(java.util.HashSet)

Example 90 with OAuth2AuthorizedClient

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

the class OAuth2ClientConfigurerTests method configureWhenAuthorizationCodeResponseSuccessThenAuthorizedClientSaved.

@Test
public void configureWhenAuthorizationCodeResponseSuccessThenAuthorizedClientSaved() throws Exception {
    this.spring.register(OAuth2ClientConfig.class).autowire();
    // Setup the Authorization Request in the session
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, this.registration1.getRegistrationId());
    // @formatter:off
    OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode().authorizationUri(this.registration1.getProviderDetails().getAuthorizationUri()).clientId(this.registration1.getClientId()).redirectUri("http://localhost/client-1").state("state").attributes(attributes).build();
    // @formatter:on
    AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
    MockHttpServletResponse response = new MockHttpServletResponse();
    authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
    MockHttpSession session = (MockHttpSession) request.getSession();
    String principalName = "user1";
    TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
    // @formatter:off
    MockHttpServletRequestBuilder clientRequest = get("/client-1").param(OAuth2ParameterNames.CODE, "code").param(OAuth2ParameterNames.STATE, "state").with(authentication(authentication)).session(session);
    this.mockMvc.perform(clientRequest).andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("http://localhost/client-1"));
    // @formatter:on
    OAuth2AuthorizedClient authorizedClient = authorizedClientRepository.loadAuthorizedClient(this.registration1.getRegistrationId(), authentication, request);
    assertThat(authorizedClient).isNotNull();
}
Also used : HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) HttpSessionOAuth2AuthorizationRequestRepository(org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository) MockHttpSession(org.springframework.mock.web.MockHttpSession) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)140 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)123 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)66 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)51 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)45 Instant (java.time.Instant)43 Authentication (org.springframework.security.core.Authentication)41 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)36 ClientRequest (org.springframework.web.reactive.function.client.ClientRequest)34 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)32 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)31 OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)31 BeforeEach (org.junit.jupiter.api.BeforeEach)28 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)23 Map (java.util.Map)21 HashMap (java.util.HashMap)20 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)19 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)17 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)17 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)17