Spring OAuth2-如何一起使用授权类型`password`和`client_credentials`,但到期时间不同

时间:2019-01-28 10:17:49

标签: spring spring-boot spring-security oauth-2.0 access-token

我正在使用Spring Security OAuth2在Web应用程序和中央授权服务器之间实现身份验证。我同时使用授权类型passwordclient_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

1 个答案:

答案 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);
    }
}