Search in sources :

Example 61 with OAuth2AccessToken

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

the class JwtBearerReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenJwtBearerAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize.

@Test
public void authorizeWhenJwtBearerAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
    Instant now = Instant.now();
    Instant issuedAt = now.minus(Duration.ofMinutes(60));
    Instant expiresAt = now.plus(Duration.ofMinutes(1));
    OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", issuedAt, expiresAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), expiresInOneMinAccessToken);
    // Shorten the lifespan of the access token by 90 seconds, which will ultimately
    // force it to expire on the client
    this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
    // @formatter:on
    OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
    assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
    assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) Test(org.junit.jupiter.api.Test)

Example 62 with OAuth2AccessToken

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

the class DefaultMapOAuth2AccessTokenResponseConverterTests method shouldConvertFull.

@Test
public void shouldConvertFull() {
    Map<String, Object> map = new HashMap<>();
    map.put("access_token", "access-token-1234");
    map.put("token_type", "bearer");
    map.put("expires_in", "3600");
    map.put("scope", "read write");
    map.put("refresh_token", "refresh-token-1234");
    map.put("custom_parameter_1", "custom-value-1");
    map.put("custom_parameter_2", "custom-value-2");
    OAuth2AccessTokenResponse converted = this.messageConverter.convert(map);
    OAuth2AccessToken accessToken = converted.getAccessToken();
    Assertions.assertNotNull(accessToken);
    Assertions.assertEquals("access-token-1234", accessToken.getTokenValue());
    Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType());
    Set<String> scopes = accessToken.getScopes();
    Assertions.assertNotNull(scopes);
    Assertions.assertEquals(2, scopes.size());
    Assertions.assertTrue(scopes.contains("read"));
    Assertions.assertTrue(scopes.contains("write"));
    Assertions.assertEquals(3600, Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds());
    OAuth2RefreshToken refreshToken = converted.getRefreshToken();
    Assertions.assertNotNull(refreshToken);
    Assertions.assertEquals("refresh-token-1234", refreshToken.getTokenValue());
    Map<String, Object> additionalParameters = converted.getAdditionalParameters();
    Assertions.assertNotNull(additionalParameters);
    Assertions.assertEquals(2, additionalParameters.size());
    Assertions.assertEquals("custom-value-1", additionalParameters.get("custom_parameter_1"));
    Assertions.assertEquals("custom-value-2", additionalParameters.get("custom_parameter_2"));
}
Also used : OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Test(org.junit.jupiter.api.Test)

Example 63 with OAuth2AccessToken

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

the class DefaultMapOAuth2AccessTokenResponseConverterTests method shouldConvertWithObjectAdditionalParameter.

// gh-9685
@Test
public void shouldConvertWithObjectAdditionalParameter() {
    Map<String, Object> map = new HashMap<>();
    map.put("access_token", "access-token-1234");
    map.put("token_type", "bearer");
    map.put("expires_in", "3600");
    map.put("scope", "read write");
    map.put("refresh_token", "refresh-token-1234");
    Map<String, Object> nestedObject = new LinkedHashMap<>();
    nestedObject.put("a", "first value");
    nestedObject.put("b", "second value");
    map.put("custom_parameter_1", nestedObject);
    map.put("custom_parameter_2", "custom-value-2");
    OAuth2AccessTokenResponse converted = this.messageConverter.convert(map);
    OAuth2AccessToken accessToken = converted.getAccessToken();
    Assertions.assertNotNull(accessToken);
    Assertions.assertEquals("access-token-1234", accessToken.getTokenValue());
    Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType());
    Set<String> scopes = accessToken.getScopes();
    Assertions.assertNotNull(scopes);
    Assertions.assertEquals(2, scopes.size());
    Assertions.assertTrue(scopes.contains("read"));
    Assertions.assertTrue(scopes.contains("write"));
    Assertions.assertEquals(3600, Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds());
    OAuth2RefreshToken refreshToken = converted.getRefreshToken();
    Assertions.assertNotNull(refreshToken);
    Assertions.assertEquals("refresh-token-1234", refreshToken.getTokenValue());
    Map<String, Object> additionalParameters = converted.getAdditionalParameters();
    Assertions.assertNotNull(additionalParameters);
    Assertions.assertEquals(2, additionalParameters.size());
    Assertions.assertEquals(nestedObject, additionalParameters.get("custom_parameter_1"));
    Assertions.assertEquals("custom-value-2", additionalParameters.get("custom_parameter_2"));
}
Also used : OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.jupiter.api.Test)

Example 64 with OAuth2AccessToken

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

the class SecurityMockMvcRequestPostProcessorsOAuth2ClientTests method oauth2ClientWhenAccessTokenThenUses.

@Test
public void oauth2ClientWhenAccessTokenThenUses() throws Exception {
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes();
    this.mvc.perform(get("/access-token").with(oauth2Client("registration-id").accessToken(accessToken))).andExpect(content().string("no-scopes"));
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Test(org.junit.jupiter.api.Test)

Example 65 with OAuth2AccessToken

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

the class OAuth2LoginTests method oauth2LoginWhenCustomObjectsInLambdaThenUsed.

@Test
public void oauth2LoginWhenCustomObjectsInLambdaThenUsed() {
    this.spring.register(OAuth2LoginWithSingleClientRegistrations.class, OAuth2LoginMockAuthenticationManagerInLambdaConfig.class).autowire();
    String redirectLocation = "/custom-redirect-location";
    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(this.springSecurity).build();
    OAuth2LoginMockAuthenticationManagerInLambdaConfig config = this.spring.getContext().getBean(OAuth2LoginMockAuthenticationManagerInLambdaConfig.class);
    ServerAuthenticationConverter converter = config.authenticationConverter;
    ReactiveAuthenticationManager manager = config.manager;
    ServerWebExchangeMatcher matcher = config.matcher;
    ServerOAuth2AuthorizationRequestResolver resolver = config.resolver;
    ServerAuthenticationSuccessHandler successHandler = config.successHandler;
    OAuth2AuthorizationExchange exchange = TestOAuth2AuthorizationExchanges.success();
    OAuth2User user = TestOAuth2Users.create();
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes();
    OAuth2LoginAuthenticationToken result = new OAuth2LoginAuthenticationToken(github, exchange, user, user.getAuthorities(), accessToken);
    given(converter.convert(any())).willReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
    given(manager.authenticate(any())).willReturn(Mono.just(result));
    given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
    given(resolver.resolve(any())).willReturn(Mono.empty());
    given(successHandler.onAuthenticationSuccess(any(), any())).willAnswer((Answer<Mono<Void>>) (invocation) -> {
        WebFilterExchange webFilterExchange = invocation.getArgument(0);
        Authentication authentication = invocation.getArgument(1);
        return new RedirectServerAuthenticationSuccessHandler(redirectLocation).onAuthenticationSuccess(webFilterExchange, authentication);
    });
    // @formatter:off
    webTestClient.get().uri("/login/oauth2/code/github").exchange().expectStatus().is3xxRedirection().expectHeader().valueEquals("Location", redirectLocation);
    // @formatter:on
    verify(converter).convert(any());
    verify(manager).authenticate(any());
    verify(matcher).matches(any());
    verify(resolver).resolve(any());
    verify(successHandler).onAuthenticationSuccess(any(), any());
}
Also used : ServerAuthorizationRequestRepository(org.springframework.security.oauth2.client.web.server.ServerAuthorizationRequestRepository) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Autowired(org.springframework.beans.factory.annotation.Autowired) WebHandler(org.springframework.web.server.WebHandler) WebTestClientHtmlUnitDriverBuilder(org.springframework.security.htmlunit.server.WebTestClientHtmlUnitDriverBuilder) WebFilterExchange(org.springframework.security.web.server.WebFilterExchange) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ReactiveUserDetailsService(org.springframework.security.core.userdetails.ReactiveUserDetailsService) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TestOidcUsers(org.springframework.security.oauth2.core.oidc.user.TestOidcUsers) WebFilter(org.springframework.web.server.WebFilter) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) AuthenticationException(org.springframework.security.core.AuthenticationException) Jwt(org.springframework.security.oauth2.jwt.Jwt) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) WebFilterChain(org.springframework.web.server.WebFilterChain) OidcClientInitiatedServerLogoutSuccessHandler(org.springframework.security.oauth2.client.oidc.web.server.logout.OidcClientInitiatedServerLogoutSuccessHandler) TestOAuth2AuthorizationExchanges(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges) ReactiveAuthenticationTestConfiguration(org.springframework.security.config.users.ReactiveAuthenticationTestConfiguration) HttpHeaders(org.springframework.http.HttpHeaders) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) ServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) RestController(org.springframework.web.bind.annotation.RestController) Test(org.junit.jupiter.api.Test) Configuration(org.springframework.context.annotation.Configuration) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) SecurityContext(org.springframework.security.core.context.SecurityContext) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) ReactiveJwtDecoderFactory(org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory) Authentication(org.springframework.security.core.Authentication) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) ServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository) RedirectServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ServerOAuth2AuthorizationRequestResolver(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizationRequestResolver) ServerWebExchangeMatcher(org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) WebDriver(org.openqa.selenium.WebDriver) 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) Mockito.spy(org.mockito.Mockito.spy) OidcAuthorizationCodeReactiveAuthenticationManager(org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeReactiveAuthenticationManager) RedirectServerAuthenticationFailureHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationFailureHandler) ServerWebExchange(org.springframework.web.server.ServerWebExchange) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) Answer(org.mockito.stubbing.Answer) SecurityContextServerLogoutHandler(org.springframework.security.web.server.authentication.logout.SecurityContextServerLogoutHandler) EnableWebFlux(org.springframework.web.reactive.config.EnableWebFlux) EnableWebFluxSecurity(org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity) CommonOAuth2Provider(org.springframework.security.config.oauth2.client.CommonOAuth2Provider) ReactiveOAuth2UserService(org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService) JwtValidationException(org.springframework.security.oauth2.jwt.JwtValidationException) GetMapping(org.springframework.web.bind.annotation.GetMapping) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestOAuth2Users(org.springframework.security.oauth2.core.user.TestOAuth2Users) WebTestClientBuilder(org.springframework.security.test.web.reactive.server.WebTestClientBuilder) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ServerSecurityContextRepository(org.springframework.security.web.server.context.ServerSecurityContextRepository) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) ServerRequestCache(org.springframework.security.web.server.savedrequest.ServerRequestCache) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Mono(reactor.core.publisher.Mono) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ApplicationContext(org.springframework.context.ApplicationContext) WebFilterChainProxy(org.springframework.security.web.server.WebFilterChainProxy) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Mockito.verify(org.mockito.Mockito.verify) InMemoryReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) SpringTestContext(org.springframework.security.config.test.SpringTestContext) TestOAuth2AuthorizationResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses) SpringTestContextExtension(org.springframework.security.config.test.SpringTestContextExtension) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Bean(org.springframework.context.annotation.Bean) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) UserDetailsRepositoryReactiveAuthenticationManager(org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager) ServerAuthenticationFailureHandler(org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) OidcAuthorizationCodeReactiveAuthenticationManager(org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeReactiveAuthenticationManager) UserDetailsRepositoryReactiveAuthenticationManager(org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) ServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler) RedirectServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler) Mono(reactor.core.publisher.Mono) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) WebFilterExchange(org.springframework.security.web.server.WebFilterExchange) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) ServerWebExchangeMatcher(org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher) ServerOAuth2AuthorizationRequestResolver(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizationRequestResolver) RedirectServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)265 Test (org.junit.Test)177 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)144 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)93 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)71 Test (org.junit.jupiter.api.Test)48 Date (java.util.Date)44 Authentication (org.springframework.security.core.Authentication)41 HashMap (java.util.HashMap)39 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)35 Instant (java.time.Instant)32 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)31 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)28 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)26 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)21 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)20 DBUnitTest (org.orcid.test.DBUnitTest)19 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)19 OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)19 Map (java.util.Map)18