Search in sources :

Example 66 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project jhipster-registry by jhipster.

the class UaaAuthorizationHeaderUtil method retrieveNewAccessToken.

private OAuth2AccessToken retrieveNewAccessToken(ClientRegistration clientRegistration) {
    MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
    formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
    RequestEntity requestEntity = RequestEntity.post(URI.create(clientRegistration.getProviderDetails().getTokenUri())).contentType(MediaType.APPLICATION_FORM_URLENCODED).body(formParameters);
    try {
        ResponseEntity<OAuth2AccessTokenResponse> responseEntity = this.uaaRestTemplate.exchange(requestEntity, OAuth2AccessTokenResponse.class);
        return Objects.requireNonNull(responseEntity.getBody()).getAccessToken();
    } catch (OAuth2AuthorizationException e) {
        log.error("Unable to get access token", e);
        throw new OAuth2AuthenticationException(e.getError(), e);
    }
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RequestEntity(org.springframework.http.RequestEntity) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 67 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project jhipster-registry by jhipster.

the class UaaAuthorizationHeaderUtilIT method testAuthorizationHeaderWithExpiredAccessToken.

@Test
public void testAuthorizationHeaderWithExpiredAccessToken() {
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "existingTokenValue", Instant.now().minus(Duration.ofHours(1)), Instant.now().minus(Duration.ofMinutes(2)));
    authorizedClientService.saveAuthorizedClient(createAuthorizedClient(accessToken), authentication);
    doReturn(ResponseEntity.ok(createAccessTokenResponse("refreshTokenValue"))).when(restTemplate).exchange(any(RequestEntity.class), ArgumentMatchers.<Class<OAuth2AccessTokenResponse>>any());
    String authorizationHeader = authorizationHeaderUtil.getAuthorizationHeader();
    assertThat(authorizationHeader).isNotEmpty();
    assertThat(authorizationHeader).isEqualTo("Bearer refreshTokenValue");
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) RequestEntity(org.springframework.http.RequestEntity) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 68 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project spring-security by spring-projects.

the class OAuth2LoginTests method oauth2LoginWhenCustomBeansThenUsed.

@Test
public void oauth2LoginWhenCustomBeansThenUsed() {
    this.spring.register(OAuth2LoginWithMultipleClientRegistrations.class, OAuth2LoginWithCustomBeansConfig.class).autowire();
    // @formatter:off
    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(this.springSecurity).build();
    // @formatter:on
    OAuth2LoginWithCustomBeansConfig config = this.spring.getContext().getBean(OAuth2LoginWithCustomBeansConfig.class);
    OAuth2AuthorizationRequest request = TestOAuth2AuthorizationRequests.request().scope("openid").build();
    OAuth2AuthorizationResponse response = TestOAuth2AuthorizationResponses.success().build();
    OAuth2AuthorizationExchange exchange = new OAuth2AuthorizationExchange(request, response);
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.scopes("openid");
    OAuth2AuthorizationCodeAuthenticationToken token = new OAuth2AuthorizationCodeAuthenticationToken(google, exchange, accessToken);
    ServerAuthenticationConverter converter = config.authenticationConverter;
    given(converter.convert(any())).willReturn(Mono.just(token));
    ServerSecurityContextRepository securityContextRepository = config.securityContextRepository;
    given(securityContextRepository.save(any(), any())).willReturn(Mono.empty());
    given(securityContextRepository.load(any())).willReturn(authentication(token));
    Map<String, Object> additionalParameters = new HashMap<>();
    additionalParameters.put(OidcParameterNames.ID_TOKEN, "id-token");
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue()).tokenType(accessToken.getTokenType()).scopes(accessToken.getScopes()).additionalParameters(additionalParameters).build();
    // @formatter:on
    ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> tokenResponseClient = config.tokenResponseClient;
    given(tokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    OidcUser user = TestOidcUsers.create();
    ReactiveOAuth2UserService<OidcUserRequest, OidcUser> userService = config.userService;
    given(userService.loadUser(any())).willReturn(Mono.just(user));
    // @formatter:off
    webTestClient.get().uri("/login/oauth2/code/google").exchange().expectStatus().is3xxRedirection();
    // @formatter:on
    verify(config.jwtDecoderFactory).createDecoder(any());
    verify(tokenResponseClient).getTokenResponse(any());
    verify(securityContextRepository).save(any(), any());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) HashMap(java.util.HashMap) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) ServerSecurityContextRepository(org.springframework.security.web.server.context.ServerSecurityContextRepository) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 69 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project spring-security by spring-projects.

the class OAuth2ClientConfigurationTests method requestWhenAuthorizedClientNotFoundAndClientCredentialsThenTokenResponseClientIsUsed.

@Test
public void requestWhenAuthorizedClientNotFoundAndClientCredentialsThenTokenResponseClientIsUsed() throws Exception {
    String clientRegistrationId = "client1";
    String principalName = "user1";
    TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
    ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
    OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
    OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
    ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().registrationId(clientRegistrationId).build();
    given(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(clientRegistration);
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(300).build();
    // @formatter:on
    given(accessTokenResponseClient.getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class))).willReturn(accessTokenResponse);
    OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
    OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
    OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient;
    this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire();
    MockHttpServletRequestBuilder authenticatedRequest = get("/authorized-client").with(authentication(authentication));
    // @formatter:off
    this.mockMvc.perform(authenticatedRequest).andExpect(status().isOk()).andExpect(content().string("resolved"));
    // @formatter:on
    verify(accessTokenResponseClient, times(1)).getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class));
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) OAuth2ClientCredentialsGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) Test(org.junit.jupiter.api.Test)

Example 70 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse in project spring-security by spring-projects.

the class OAuth2LoginBeanDefinitionParserTests method requestWhenCustomAuthorizedClientServiceThenCalled.

@Test
public void requestWhenCustomAuthorizedClientServiceThenCalled() throws Exception {
    this.spring.configLocations(this.xml("WithCustomAuthorizedClientService")).autowire();
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
    given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(clientRegistration);
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId());
    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());
    this.mvc.perform(get("/login/oauth2/code/" + clientRegistration.getRegistrationId()).params(params));
    verify(this.authorizedClientService).saveAuthorizedClient(any(), any());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)134 Test (org.junit.jupiter.api.Test)122 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)43 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)40 Instant (java.time.Instant)37 HashMap (java.util.HashMap)32 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)27 Mono (reactor.core.publisher.Mono)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)16 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)16 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)15 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)15 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)14 BeforeEach (org.junit.jupiter.api.BeforeEach)13 Map (java.util.Map)12 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)11 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11