我正在使用Spring Security OAuth2在Web应用程序和中央授权服务器之间实现身份验证。我同时使用授权类型password
和client_credentials
。当用户尚未登录时,Web应用程序将使用client_credentials
令牌,而在用户尚未登录时,Web应用程序将使用password
令牌。
对于password
令牌,我将到期时间设置为较短,并提供了一个长寿命的刷新令牌来更新访问令牌。通过更改表access_token_validity
中列oauth_client_details
的值来完成到期时间配置。
| client_id | authorized_grant_types | access_token_validity |
----------------------------------------------------------------------------------
my_web_app password,refresh_token,client_credentials 900
但是对于client_credentials
令牌,我想使其永不过期。但是,Spring对两种类型的令牌都使用access_token_validity
中的值。
如何为两种令牌类型分别设置access_token_validity
?
答案 0 :(得分:0)
研究代码,我提出了以下解决方案。
首先,将{ "client_token_validity": 2000000000 }
添加到表additional_information
的列oauth_client_details
中
| client_id | authorized_grant_types | access_token_validity | additional_information
----------------------------------------------------------------------------------------------------------------------------------------------------------
my_web_app password,refresh_token,client_credentials 900 { "client_token_validity": 2000000000 }
然后,扩展DefaultTokenServices
,覆盖方法getAccessTokenValiditySeconds
,以读取上述附加信息。
@Autowired
private DataSource dataSource;
@Bean
public ClientDetailsService clientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
MyJwtTokenService myJwtTokenService = new MyJwtTokenService(tokenBlackListService);
tokenServices.setClientDetailsService(clientDetailsService());
return myJwtTokenService;
}
public class MyJwtTokenService extends DefaultTokenServices {
private ClientDetailsService clientDetailsService;
@Override
public void setClientDetailsService(ClientDetailsService clientDetailsService) {
this.clientDetailsService = clientDetailsService;
super.setClientDetailsService(clientDetailsService);
}
@Override
protected int getAccessTokenValiditySeconds(OAuth2Request clientAuth) {
String grantType = clientAuth.getGrantType();
if ("client_credentials".equals(grantType)) {
ClientDetails client = this.clientDetailsService.loadClientByClientId(clientAuth.getClientId());
Object clientTokenValidity = client.getAdditionalInformation().get("client_token_validity");
if (clientTokenValidity != null) {
return (int) clientTokenValidity;
}
}
return super.getAccessTokenValiditySeconds(clientAuth);
}
}