org.springframework.security.oauth2.common.OAuth2RefreshToken Java Examples

The following examples show how to use org.springframework.security.oauth2.common.OAuth2RefreshToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MongoTokenStore.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2RefreshToken readRefreshToken(String tokenValue) {
    LOG.debug("Call readRefreshToken, tokenValue = {}", tokenValue);
    OAuth2RefreshToken refreshToken = null;

    try {
        final String tokenId = extractTokenKey(tokenValue);

        RefreshToken refreshTokenFounded = refreshTokenRepository.findOne(tokenId);
        refreshToken = refreshTokenFounded == null ? null : refreshTokenFounded.token();
    } catch (IllegalArgumentException e) {
        LOG.warn("Failed to deserialize refresh token for token {}", tokenValue);
        removeRefreshToken(tokenValue);
    }

    return refreshToken;
}
 
Example #2
Source File: MongoTokenStoreTest.java    From spring-security-mongo with MIT License 6 votes vote down vote up
@Test
public void shouldStoreRefreshToken() {
    //Given
    final OAuth2RefreshToken oAuth2RefreshToken = OAuth2RefreshTokenBuilder.oAuth2RefreshToken().build();

    //And
    final OAuth2Authentication oAuth2Authentication = OAuth2AuthenticationBuilder.oAuth2AuthenticationBuilder().build();

    //And
    final ArgumentCaptor<MongoOAuth2RefreshToken> argumentCaptor = ArgumentCaptor.forClass(MongoOAuth2RefreshToken.class);

    //When
    mongoTokenStore.storeRefreshToken(oAuth2RefreshToken, oAuth2Authentication);

    //Then
    verify(mongoOAuth2RefreshTokenRepository).save(argumentCaptor.capture());
    final MongoOAuth2RefreshToken refreshToken = argumentCaptor.getValue();
    final byte[] expectedResult = SerializationUtils.serialize(oAuth2RefreshToken);
    assertThat(refreshToken.getToken()).isEqualTo(expectedResult);

}
 
Example #3
Source File: HomeController.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
/**
 * 清除token(注销登录)
 */
@SysLog("登出")
@DeleteMapping("/logout")
@ApiOperation(value = "登出")
public ApiResponse logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
    if (StringUtils.isBlank(authHeader)) {
        return fail("退出失败,token 为空");
    }
    //注销当前用户
    String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StringUtils.EMPTY).trim();
    OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
    tokenStore.removeAccessToken(accessToken);
    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    tokenStore.removeRefreshToken(refreshToken);
    return success("注销成功");
}
 
Example #4
Source File: HomeController.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
/**
 * 清除token(注销登录)
 */
@SysLog("登出")
@DeleteMapping("/logout")
@ApiOperation(value = "登出")
public ApiResponse logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
    if (StringUtils.isBlank(authHeader)) {
        return fail("退出失败,token 为空");
    }
    //注销当前用户
    String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StringUtils.EMPTY).trim();
    OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
    tokenStore.removeAccessToken(accessToken);
    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    tokenStore.removeRefreshToken(refreshToken);
    return success("注销成功");
}
 
Example #5
Source File: OAuth2CookieHelper.java    From cubeai with Apache License 2.0 6 votes vote down vote up
/**
 * Create cookies using the provided values.
 *
 * @param request     the request we are handling.
 * @param accessToken the access token and enclosed refresh token for our cookies.
 * @param rememberMe  whether the user had originally checked "remember me".
 * @param result      will get the resulting cookies set.
 */
public void createCookies(HttpServletRequest request, OAuth2AccessToken accessToken, boolean rememberMe,
                          OAuth2Cookies result) {
    String domain = getCookieDomain(request);
    log.debug("creating cookies for domain {}", domain);
    Cookie accessTokenCookie = new Cookie(ACCESS_TOKEN_COOKIE, accessToken.getValue());
    setCookieProperties(accessTokenCookie, request.isSecure(), domain);
    log.debug("created access token cookie '{}'", accessTokenCookie.getName());

    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    Cookie refreshTokenCookie = createRefreshTokenCookie(refreshToken, rememberMe);
    setCookieProperties(refreshTokenCookie, request.isSecure(), domain);
    log.debug("created refresh token cookie '{}', age: {}", refreshTokenCookie.getName(), refreshTokenCookie
        .getMaxAge());

    result.setCookies(accessTokenCookie, refreshTokenCookie);
}
 
Example #6
Source File: OAuth2CookieHelper.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Create a cookie out of the given refresh token.
 * Refresh token cookies contain the base64 encoded refresh token (a JWT token).
 * They also contain a hint whether the refresh token was for remember me or not.
 * If not, then the cookie will be prefixed by the timestamp it was created at followed by a pipe '|'.
 * This gives us the chance to expire session cookies regardless of the token duration.
 */
private Cookie createRefreshTokenCookie(OAuth2RefreshToken refreshToken, boolean rememberMe) {
    int maxAge = -1;
    String name = SESSION_TOKEN_COOKIE;
    String value = refreshToken.getValue();
    if (rememberMe) {
        name = REFRESH_TOKEN_COOKIE;
        //get expiration in seconds from the token's "exp" claim
        Integer exp = getClaim(refreshToken.getValue(), AccessTokenConverter.EXP, Integer.class);
        if (exp != null) {
            int now = (int) (System.currentTimeMillis() / 1000L);
            maxAge = exp - now;
            log.debug("refresh token valid for another {} secs", maxAge);
            //let cookie expire a bit earlier than the token to avoid race conditions
            maxAge -= REFRESH_TOKEN_EXPIRATION_WINDOW_SECS;
        }
    }
    Cookie refreshTokenCookie = new Cookie(name, value);
    refreshTokenCookie.setMaxAge(maxAge);
    return refreshTokenCookie;
}
 
Example #7
Source File: OAuth2CookieHelper.java    From cubeai with Apache License 2.0 6 votes vote down vote up
/**
 * Create a cookie out of the given refresh token.
 * Refresh token cookies contain the base64 encoded refresh token (a JWT token).
 * They also contain a hint whether the refresh token was for remember me or not.
 * If not, then the cookie will be prefixed by the timestamp it was created at followed by a pipe '|'.
 * This gives us the chance to expire session cookies regardless of the token duration.
 */
private Cookie createRefreshTokenCookie(OAuth2RefreshToken refreshToken, boolean rememberMe) {
    int maxAge = -1;
    String name = SESSION_TOKEN_COOKIE;
    String value = refreshToken.getValue();
    if (rememberMe) {
        name = REFRESH_TOKEN_COOKIE;
        //get expiration in seconds from the token's "exp" claim
        Integer exp = getClaim(refreshToken.getValue(), AccessTokenConverter.EXP, Integer.class);
        if (exp != null) {
            int now = (int) (System.currentTimeMillis() / 1000L);
            maxAge = exp - now;
            log.debug("refresh token valid for another {} secs", maxAge);
            //let cookie expire a bit earlier than the token to avoid race conditions
            maxAge -= REFRESH_TOKEN_EXPIRATION_WINDOW_SECS;
        }
    }
    Cookie refreshTokenCookie = new Cookie(name, value);
    refreshTokenCookie.setMaxAge(maxAge);
    return refreshTokenCookie;
}
 
Example #8
Source File: OAuth2CookieHelper.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Create cookies using the provided values.
 *
 * @param request     the request we are handling.
 * @param accessToken the access token and enclosed refresh token for our cookies.
 * @param rememberMe  whether the user had originally checked "remember me".
 * @param result      will get the resulting cookies set.
 */
public void createCookies(HttpServletRequest request, OAuth2AccessToken accessToken, boolean rememberMe,
                          OAuth2Cookies result) {
    String domain = getCookieDomain(request);
    log.debug("creating cookies for domain {}", domain);
    Cookie accessTokenCookie = new Cookie(ACCESS_TOKEN_COOKIE, accessToken.getValue());
    setCookieProperties(accessTokenCookie, request.isSecure(), domain);
    log.debug("created access token cookie '{}'", accessTokenCookie.getName());

    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    Cookie refreshTokenCookie = createRefreshTokenCookie(refreshToken, rememberMe);
    setCookieProperties(refreshTokenCookie, request.isSecure(), domain);
    log.debug("created refresh token cookie '{}', age: {}", refreshTokenCookie.getName(), refreshTokenCookie
        .getMaxAge());

    result.setCookies(accessTokenCookie, refreshTokenCookie);
}
 
Example #9
Source File: CustomJwtTokenEnhancer.java    From fast-family-master with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
    if (oAuth2AccessToken instanceof DefaultOAuth2AccessToken) {
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) oAuth2AccessToken;
        String clientId = oAuth2Authentication.getOAuth2Request().getClientId();
        Date expiration = oAuth2AccessToken.getExpiration();
        String createToken = createToken(clientId, expiration);
        token.setValue(createToken);
        OAuth2RefreshToken refreshToken = oAuth2AccessToken.getRefreshToken();
        if (refreshToken instanceof DefaultOAuth2AccessToken) {
            token.setRefreshToken(new DefaultOAuth2RefreshToken(createToken(clientId, expiration)));
        }
        Map<String, Object> additionalInformation = new HashMap<>();
        additionalInformation.put("client_id", oAuth2Authentication.getOAuth2Request().getClientId());
        token.setAdditionalInformation(additionalInformation);
        return token;
    }
    return oAuth2AccessToken;
}
 
Example #10
Source File: OAuth2TokenDAOTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void readAuthenticationForRefreshToken() throws Exception {
    when(this.stat.executeQuery()).thenReturn(res);
    Mockito.when(res.next()).thenReturn(true).thenReturn(false);
    Mockito.when(res.getString("localuser")).thenReturn("username");
    Mockito.when(res.getString("clientid")).thenReturn("client_id");
    Mockito.when(res.getString("granttype")).thenReturn("password");
    OAuth2RefreshToken refreshToken = new DefaultOAuth2RefreshToken("value_X1");
    OAuth2Authentication auth = this.tokenDAO.readAuthenticationForRefreshToken(refreshToken);
    Assert.assertNotNull(auth);
    Assert.assertEquals("username", auth.getPrincipal());
    Assert.assertEquals("password", auth.getOAuth2Request().getGrantType());
    Mockito.verify(stat, Mockito.times(1)).setString(Mockito.anyInt(), Mockito.anyString());
    Mockito.verify(res, Mockito.times(3)).getString(Mockito.anyString());
    Mockito.verify(res, Mockito.times(0)).getTimestamp(Mockito.anyString());
    Mockito.verify(stat, Mockito.times(1)).close();
    Mockito.verify(res, Mockito.times(1)).close();
    Mockito.verify(conn, Mockito.times(1)).close();
}
 
Example #11
Source File: CustomRedisTokenStore.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
    byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue());
    byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue());
    byte[] serializedRefreshToken = serialize(refreshToken);
    RedisConnection conn = getConnection();
    try {
        conn.openPipeline();
        if (springDataRedis_2_0) {
            try {
                this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken);
                this.redisConnectionSet_2_0.invoke(conn, refreshAuthKey, serialize(authentication));
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        } else {
            conn.set(refreshKey, serializedRefreshToken);
            conn.set(refreshAuthKey, serialize(authentication));
        }
        expireRefreshToken(refreshToken, conn, refreshKey, refreshAuthKey);
        conn.closePipeline();
    } finally {
        conn.close();
    }
}
 
Example #12
Source File: OAuth2TokenDAOTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test(expected = RuntimeException.class)
public void failReadRefreshToken() throws Exception {
    try {
        when(this.statForSearchId.executeQuery()).thenReturn(resForSearchId);
        when(resForSearchId.next()).thenReturn(true).thenReturn(false);
        when(resForSearchId.getString(Mockito.anyString())).thenThrow(SQLException.class);
        OAuth2RefreshToken refreshToken = this.tokenDAO.readRefreshToken("refresh");
        Assert.fail();
    } catch (RuntimeException e) {
        Mockito.verify(statForSearchId, Mockito.times(1)).setString(Mockito.anyInt(), Mockito.anyString());
        Mockito.verify(resForSearchId, Mockito.times(1)).getString(Mockito.anyString());
        this.executeFinalCheckForSearchId(true);
        Mockito.verify(conn, Mockito.times(1)).close();
        throw e;
    }
}
 
Example #13
Source File: OAuth2TokenDAOTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test(expected = RuntimeException.class)
public void failReadAuthenticationForRefreshToken() throws Exception {
    OAuth2RefreshToken refreshToken = new DefaultOAuth2RefreshToken("value_X2");
    try {
        when(this.stat.executeQuery()).thenReturn(res);
        Mockito.when(res.next()).thenReturn(true).thenReturn(false);
        Mockito.when(res.getString("localuser")).thenReturn("username");
        Mockito.when(res.getString("clientid")).thenThrow(SQLException.class);
        Mockito.when(res.getString("granttype")).thenReturn("password");
        OAuth2Authentication auth = this.tokenDAO.readAuthenticationForRefreshToken(refreshToken);
        Assert.fail();
    } catch (RuntimeException e) {
        Mockito.verify(stat, Mockito.times(1)).setString(Mockito.anyInt(), Mockito.anyString());
        Mockito.verify(res, Mockito.times(2)).getString(Mockito.anyString());
        Mockito.verify(res, Mockito.times(0)).getTimestamp(Mockito.anyString());
        Mockito.verify(stat, Mockito.times(1)).close();
        Mockito.verify(res, Mockito.times(1)).close();
        Mockito.verify(conn, Mockito.times(1)).close();
        throw e;
    }
}
 
Example #14
Source File: OauthLogoutHandler.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
	Assert.notNull(tokenStore, "tokenStore must be set");
	String token = extractToken(request);
	if(token!=null || !"".equals(token)){
		OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
		OAuth2RefreshToken refreshToken;
		if (existingAccessToken != null) {
			if (existingAccessToken.getRefreshToken() != null) {
				logger.info("remove refreshToken!", existingAccessToken.getRefreshToken());
				refreshToken = existingAccessToken.getRefreshToken();
				tokenStore.removeRefreshToken(refreshToken);
			}
			logger.info("remove existingAccessToken!", existingAccessToken);
			tokenStore.removeAccessToken(existingAccessToken);
		}
		return;
	}

}
 
Example #15
Source File: MongoTokenStoreTest.java    From spring-security-mongo with MIT License 6 votes vote down vote up
@Test
public void shouldReadRefreshToken() {
    //Given
    final String tokenValue = string().next();
    final OAuth2RefreshToken oAuth2RefreshToken = OAuth2RefreshTokenBuilder.oAuth2RefreshToken().build();
    final byte[] oAuth2RefreshTokenSer = SerializationUtils.serialize(oAuth2RefreshToken);

    //And
    given(mongoOAuth2RefreshTokenRepository.findByTokenId(any(String.class)))
            .willReturn(MongoOAuth2RefreshTokenBuilder.mongoOAuth2RefreshTokenBuilder().token(oAuth2RefreshTokenSer).build());

    //When
    final OAuth2RefreshToken result = mongoTokenStore.readRefreshToken(tokenValue);

    //Then
    assertThat(result.getValue()).isEqualTo(oAuth2RefreshToken.getValue());
}
 
Example #16
Source File: SmartlingAuthorizationCodeAccessTokenProvider.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest accessTokenRequest) throws UserRedirectRequiredException {

    logger.debug("Get refresh token");

    SmartlingOAuth2ProtectedResourceDetails smartlingOAuth2ProtectedResourceDetails = (SmartlingOAuth2ProtectedResourceDetails) resource;
    Map<String, String> request = new HashMap<>();
    request.put("refreshToken", refreshToken.getValue());

    DefaultOAuth2AccessToken defaultOAuth2AccessToken = null;
    try {
        DateTime now = getNowForToken();
        AuthenticationResponse authenticationResponse = restTemplate.postForObject(smartlingOAuth2ProtectedResourceDetails.getRefreshUri(), request, AuthenticationResponse.class);
        defaultOAuth2AccessToken = getDefaultOAuth2AccessToken(now, authenticationResponse);
    } catch (Exception e) {
        String msg = "Can't get Smartling refresh token";
        logger.debug(msg, e);
        throw new OAuth2AccessDeniedException(msg, resource, e);
    }

    return defaultOAuth2AccessToken;
}
 
Example #17
Source File: CustomLogoutHandler.java    From microservice-integration with MIT License 6 votes vote down vote up
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    Assert.notNull(tokenStore, "tokenStore must be set");
    String token = request.getHeader("Authorization");
    Assert.hasText(token, "token must be set");
    if (isJwtBearerToken(token)) {
        token = token.substring(6);
        OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
        OAuth2RefreshToken refreshToken;
        if (existingAccessToken != null) {
            if (existingAccessToken.getRefreshToken() != null) {
                LOGGER.info("remove refreshToken!", existingAccessToken.getRefreshToken());
                refreshToken = existingAccessToken.getRefreshToken();
                tokenStore.removeRefreshToken(refreshToken);
            }
            LOGGER.info("remove existingAccessToken!", existingAccessToken);
            tokenStore.removeAccessToken(existingAccessToken);
        }
        return;
    } else {
        throw new BadClientCredentialsException();
    }

}
 
Example #18
Source File: CustomLogoutHandler.java    From Auth-service with MIT License 6 votes vote down vote up
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    Assert.notNull(tokenStore, "tokenStore must be set");
    String token = request.getHeader("Authorization");
    Assert.hasText(token, "token must be set");
    if (isJwtBearerToken(token)) {
        token = token.substring(6).trim();
        OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
        OAuth2RefreshToken refreshToken;
        if (existingAccessToken != null) {
            if (existingAccessToken.getRefreshToken() != null) {
                LOGGER.info("remove refreshToken!", existingAccessToken.getRefreshToken());
                refreshToken = existingAccessToken.getRefreshToken();
                tokenStore.removeRefreshToken(refreshToken);
            }
            LOGGER.info("remove existingAccessToken!", existingAccessToken);
            tokenStore.removeAccessToken(existingAccessToken);
        }
        return;
    } else {
        throw new BadClientCredentialsException();
    }

}
 
Example #19
Source File: GsonSerializerOAuth2AccessToken.java    From NFVO with Apache License 2.0 5 votes vote down vote up
@Override
public JsonElement serialize(
    OAuth2AccessToken src, Type typeOfSrc, JsonSerializationContext context) {
  JsonObject jsonObject = new JsonObject();
  jsonObject.addProperty(OAuth2AccessToken.ACCESS_TOKEN, src.getValue());
  // back compatibility for dashboard
  jsonObject.addProperty("value", src.getValue());

  jsonObject.addProperty(OAuth2AccessToken.TOKEN_TYPE, src.getTokenType());

  OAuth2RefreshToken refreshToken = src.getRefreshToken();
  if (refreshToken != null) {
    jsonObject.addProperty(OAuth2AccessToken.REFRESH_TOKEN, refreshToken.getValue());
  }
  Date expiration = src.getExpiration();
  if (expiration != null) {
    long now = System.currentTimeMillis();
    jsonObject.add(
        OAuth2AccessToken.EXPIRES_IN, new JsonPrimitive((expiration.getTime() - now) / 1000));
  }

  Set<String> scope = src.getScope();

  if (scope != null && !scope.isEmpty()) {
    StringBuilder scopes = new StringBuilder();
    for (String s : scope) {
      Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope + "");
      scopes.append(s);
      scopes.append(" ");
    }

    jsonObject.addProperty(OAuth2AccessToken.SCOPE, scopes.substring(0, scopes.length() - 1));
  }

  return jsonObject;
}
 
Example #20
Source File: GoogleFitShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(
        OAuth2ProtectedResourceDetails resource,
        OAuth2RefreshToken refreshToken, AccessTokenRequest request)
        throws UserRedirectRequiredException,
        OAuth2AccessDeniedException {

    OAuth2AccessToken accessToken = super.refreshAccessToken(resource, refreshToken, request);
    // Google does not replace refresh tokens, so we need to hold on to the existing refresh token...
    if (accessToken.getRefreshToken() == null) {
        ((DefaultOAuth2AccessToken) accessToken).setRefreshToken(refreshToken);
    }
    return accessToken;
}
 
Example #21
Source File: CustomRedisTokenStore.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2RefreshToken readRefreshToken(String tokenValue) {
    byte[] key = serializeKey(REFRESH + tokenValue);
    byte[] bytes;
    RedisConnection conn = getConnection();
    try {
        bytes = conn.get(key);
    } finally {
        conn.close();
    }
    return deserializeRefreshToken(bytes);
}
 
Example #22
Source File: CustomRedisTokenStore.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
private void expireRefreshToken(OAuth2RefreshToken refreshToken, RedisConnection conn, byte[] refreshKey, byte[] refreshAuthKey) {
    if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
        ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
        Date expiration = expiringRefreshToken.getExpiration();
        if (expiration != null) {
            int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
                    .intValue();
            conn.expire(refreshKey, seconds);
            conn.expire(refreshAuthKey, seconds);
        }
    }
}
 
Example #23
Source File: MongoTokenStore.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Override
public void storeRefreshToken(final OAuth2RefreshToken refreshToken,
                              final OAuth2Authentication oAuth2Authentication) {
    final String tokenKey = extractTokenKey(refreshToken.getValue());
    final byte[] token = serializeRefreshToken(refreshToken);
    final byte[] authentication = serializeAuthentication(oAuth2Authentication);

    final MongoOAuth2RefreshToken oAuth2RefreshToken = new MongoOAuth2RefreshToken(tokenKey, token, authentication);

    mongoOAuth2RefreshTokenRepository.save(oAuth2RefreshToken);
}
 
Example #24
Source File: MongoTokenStoreTest.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Test
public void shouldRemoveRefreshToken() {
    //Given
    final OAuth2RefreshToken oAuth2RefreshToken = OAuth2RefreshTokenBuilder.oAuth2RefreshToken().build();

    //When
    mongoTokenStore.removeRefreshToken(oAuth2RefreshToken);

    //Then
    verify(mongoOAuth2RefreshTokenRepository).deleteByTokenId(any(String.class));
}
 
Example #25
Source File: AcAccessTokenProvider.java    From cola with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException {
	MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
	form.add("grant_type", "refresh_token");
	form.add("refresh_token", refreshToken.getValue());
	return retrieveToken(request, resource, form, new HttpHeaders());
}
 
Example #26
Source File: MongoTokenStore.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
    LOG.debug("Call storeRefreshToken, refreshToken = {}, authentication = {}", refreshToken, authentication);

    RefreshToken token = new RefreshToken()
            .tokenId(extractTokenKey(refreshToken.getValue()))
            .token(refreshToken)
            .authentication(authentication);

    refreshTokenRepository.save(token);
}
 
Example #27
Source File: MongoTokenStoreTest.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Test
public void shouldRemoveAccessTokenUsingRefreshToken() {
    //Given
    final OAuth2RefreshToken oAuth2RefreshToken = OAuth2RefreshTokenBuilder.oAuth2RefreshToken().build();

    //When
    mongoTokenStore.removeAccessTokenUsingRefreshToken(oAuth2RefreshToken);

    //Then
    verify(mongoOAuth2AccessTokenRepository).deleteByRefreshTokenId(any(String.class));
}
 
Example #28
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException, OAuth2AccessDeniedException {
    MultiValueMap<String, String> form = new LinkedMultiValueMap();
    form.add("grant_type", "refresh_token");
    form.add("refresh_token", refreshToken.getValue());
    form.add("appid", resource.getClientId());

    try {
        return this.retrieveToken(request, resource, form, this.getHeadersForTokenRequest(request));
    } catch (OAuth2AccessDeniedException var6) {
        throw this.getRedirectForAuthorization((AuthorizationCodeResourceDetails)resource, request);
    }
}
 
Example #29
Source File: MongoTokenStoreTest.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Test
public void shouldReadNullWhenNoRefreshToken() {
    //Given
    final String tokenValue = string().next();

    //And
    given(mongoOAuth2RefreshTokenRepository.findByTokenId(any(String.class)))
            .willReturn(null);

    //When
    final OAuth2RefreshToken result = mongoTokenStore.readRefreshToken(tokenValue);

    //Then
    assertThat(result).isNull();
}
 
Example #30
Source File: CustomRedisTokenStore.java    From Auth-service with MIT License 5 votes vote down vote up
@Override
public OAuth2RefreshToken readRefreshToken(String tokenValue) {
    byte[] key = serializeKey(REFRESH + tokenValue);
    byte[] bytes = null;
    RedisConnection conn = getConnection();
    try {
        bytes = conn.get(key);
    } finally {
        conn.close();
    }
    OAuth2RefreshToken refreshToken = deserializeRefreshToken(bytes);
    return refreshToken;
}