Spring Boot+OAuth2,如何自定义返回的 Token 信息
在Spring Boot中,要自定义OAuth2返回的Token信息,你可以通过扩展TokenGranter
接口来创建自定义的TokenGranter
实现。以下是一个简单的例子,演示如何添加自定义的响应字段:
- 创建自定义的
TokenGranter
实现:
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import java.util.LinkedHashMap;
import java.util.Map;
public class CustomTokenGranter implements TokenGranter {
private final AuthorizationServerTokenServices tokenServices;
private final TokenGranter delegate;
public CustomTokenGranter(AuthorizationServerTokenServices tokenServices, TokenGranter delegate) {
this.tokenServices = tokenServices;
this.delegate = delegate;
}
@Override
public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
OAuth2AccessToken token = delegate.grant(grantType, tokenRequest);
if (token != null) {
// 自定义响应字段
Map<String, Object> additionalInformation = new LinkedHashMap<>(token.getAdditionalInformation());
additionalInformation.put("custom_field", "custom_value");
// 创建一个新的token,添加自定义信息
DefaultOAuth2AccessToken customToken = new DefaultOAuth2AccessToken(token);
customToken.setAdditionalInformation(additionalInformation);
return customToken;
}
return token;
}
}
- 注册自定义
TokenGranter
:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
@Configuration
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
private final TokenGranter tokenGranter;
private final AuthorizationServerTokenServices tokenServices;
public OAuth2Config(TokenGranter tokenGranter, AuthorizationServerTokenServices tokenServices) {
this.tokenGranter = tokenGranter;
this.tokenServices = tokenServices;
}
@Bean
public TokenGranter tokenGrante
评论已关闭