Search in sources :

Example 76 with OAuth2AccessToken

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

the class PasswordReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenPasswordAndAuthorizedWithoutRefreshTokenAndTokenExpiredThenReauthorize.

@Test
public void authorizeWhenPasswordAndAuthorizedWithoutRefreshTokenAndTokenExpiredThenReauthorize() {
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
    OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-expired", issuedAt, expiresAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), // without refresh token
    accessToken);
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username").attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password").principal(this.principal).build();
    // @formatter:on
    authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
    assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
    assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
    assertThat(authorizedClient.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 77 with OAuth2AccessToken

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

the class ReactiveOAuth2AuthorizedClientProviderBuilderTests method expiredAccessToken.

private OAuth2AccessToken expiredAccessToken() {
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
    return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", issuedAt, expiresAt);
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant)

Example 78 with OAuth2AccessToken

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

the class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests method authorizeWhenAuthorizedAndAccessTokenNotExpiredButClockSkewForcesExpiryThenReauthorize.

// gh-7511
@Test
public void authorizeWhenAuthorizedAndAccessTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("new-refresh-token").build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    Instant now = Instant.now();
    Instant issuedAt = now.minus(Duration.ofMinutes(60));
    Instant expiresAt = now.minus(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, this.authorizedClient.getRefreshToken());
    // 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));
    OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
    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());
    assertThat(reauthorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
}
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 79 with OAuth2AccessToken

use of org.springframework.security.oauth2.core.OAuth2AccessToken in project new-cloud by xie-summer.

the class MobileLoginSuccessHandler method onAuthenticationSuccess.

/**
 * Called when a user has been successfully authenticated.
 * 调用spring security oauth API 生成 oAuth2AccessToken
 *
 * @param request        the request which caused the successful authentication
 * @param response       the response
 * @param authentication the <tt>Authentication</tt> object which was created during
 */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String header = request.getHeader("Authorization");
    if (header == null || !header.startsWith(BASIC_)) {
        throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
    }
    try {
        String[] tokens = extractAndDecodeHeader(header);
        assert tokens.length == 2;
        String clientId = tokens[0];
        String clientSecret = tokens[1];
        JSONObject params = new JSONObject();
        params.put("clientId", clientId);
        params.put("clientSecret", clientSecret);
        params.put("authentication", authentication);
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        logger.info("获取token 成功:{}", oAuth2AccessToken.getValue());
        response.setCharacterEncoding(CommonConstant.UTF8);
        response.setContentType(CommonConstant.CONTENT_TYPE);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
    } catch (IOException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) UnapprovedClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) IOException(java.io.IOException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) PrintWriter(java.io.PrintWriter)

Example 80 with OAuth2AccessToken

use of org.springframework.security.oauth2.core.OAuth2AccessToken in project new-cloud by xie-summer.

the class SocialLoginSuccessHandler method onAuthenticationSuccess.

/**
 * Called when a user has been successfully authenticated.
 * 调用spring security oauth API 生成 oAuth2AccessToken
 *
 * @param request        the request which caused the successful authentication
 * @param response       the response
 * @param authentication the <tt>Authentication</tt> object which was created during
 */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    try {
        String clientId = authServerConfig.getClientId();
        String clientSecret = authServerConfig.getClientSecret();
        JSONObject params = new JSONObject();
        params.put("clientId", clientId);
        params.put("clientSecret", clientSecret);
        params.put("authentication", authentication);
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "social");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        logger.info("获取token 成功:{}", oAuth2AccessToken.getValue());
        String url = String.format("http://localhost:9527/#/login?access_token=%s&refresh_token=%s", oAuth2AccessToken.getValue(), oAuth2AccessToken.getRefreshToken().getValue());
        logger.info("social登录,回调地址:{}", url);
        response.sendRedirect(url);
    } catch (IOException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) IOException(java.io.IOException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

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