java - 使用 Spring Oauth2 缓存访问 token

标签 java spring rest oauth oauth2resttemplate

我已经在 java spring 框架中实现了 REST Web 服务。我的应用程序需要获取访问 token 才能发出其他 URL 请求。我想缓存 token ,以便可以重复使用它,直到它过期。目前,我正在使用一个字段来存储 token ,但是还有其他使用 spring-security 类的方法吗?

这就是我获取 accesToken 的方式:

@Bean
private OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails() {
    ClientCredentialsResourceDetails details = new 
    ClientCredentialsResourceDetails();
    details.setClientId(clientId);
    details.setClientSecret(clientSecret);
    accessTokenUrl = BackEndUrl + "/oauth2/token";
    details.setAccessTokenUri(accessTokenUrl);
    return details;
}

@Bean
private OAuth2RestTemplate createRestTemplate(OAuth2ClientContext clientContext) {
    return new OAuth2RestTemplate(oAuth2ProtectedResourceDetails(), clientContext);
}

@Override
public ResponseEntity<String> service() {

    // Token recovery if no token has been created or if the token expiration time is exceeded
    if (this.strToken == null || this.tokenLimitTime.isBeforeNow()) {
        OAuth2ClientContext context = new DefaultOAuth2ClientContext();

        OAuth2RestTemplate restTemplate = createRestTemplate(context);

        OAuth2AccessToken token = restTemplate.getAccessToken();

        if (token != null) {
            this.strToken = token.getValue();
            this.tokenLimitTime = DateTime.now().plusSeconds(token.getExpiresIn());
        }
    }

最佳答案

这取决于您使用的 token 存储。例如,如果您使用 InMemoryTokenStoreJDBCTOkenStore提供了 API 来使用用户名或客户端 ID(即 public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName)public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) )访问 token 。

如果您使用 JwtTokenStore,则有 ApprovalStore机制。

关于java - 使用 Spring Oauth2 缓存访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47432934/

相关文章:

java - Spring Security protected void configure(HttpSecurity http) 请解释 "and() "的正确使用。这是什么意思?

java - @Autowired 的配置属性在 Spring Boot 中为 null

java - 如果未在 REST-ful API 中授权,则限制对字段的访问

ios - swiftydropbox 和服务器端访问 token 的使用

rest - 如何在没有资源的情况下构建 REST API?

java - 工作流设计模式与任务模式相结合?

java - 在 Spring Boot 上删除 "Using default security password"

Java CSV 文件操作

spring - 如何在实现 Condition/ConfigurationCondition 接口(interface)的类中使用 @Value 或 Environment

java - 无法确定 Hibernate PersistenceProvider