[英]Spring Boot 2 Spring-Security 5 OAuth2 support for client_credentials grant_type
[英]Spring OAuth2 - How to use grant type `password` and `client_credentials` together but with different expired time
我正在使用Spring Security OAuth2在Web應用程序和中央授權服務器之間實現身份驗證。 我將授予類型password
和client_credentials
一起使用。 當用戶尚未登錄時,Web應用程序將使用client_credentials
令牌,而在用戶已經登錄時,Web應用程序將使用password
令牌。
對於password
令牌,我將到期時間設置為較短,並提供了一個長壽命的刷新令牌來更新訪問令牌。 通過更改表oauth_client_details
access_token_validity
列的值來完成到期時間配置。
| 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
?
研究代碼,我提出以下解決方案。
首先,添加{ "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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.