能否将OAuth2认证服务器的JWT格式访问令牌改为OAuth令牌?
能否将OAuth2认证服务器的JWT访问令牌改为传统OAuth令牌?
可以,OAuth2协议支持两种类型的访问令牌,你完全可以将认证服务器配置为颁发**不透明令牌(传统OAuth令牌)**替代当前的JWT令牌。
两种令牌的核心区别
- JWT令牌:自包含式令牌,本身携带用户身份、权限、过期时间等信息,资源服务器无需调用认证服务器即可验证令牌有效性。
- 不透明令牌:一串无意义的随机字符串,资源服务器必须调用认证服务器的
/oauth2/introspect端点,才能验证令牌并获取关联的用户信息。
针对现有代码的修改方案
你当前的代码配置了JWK源用于JWT的签名与验证,要切换为不透明令牌,需要移除JWT相关配置,改用令牌存储组件:
移除JWT相关Bean
删除原代码中jwkSource()、generateRsa()、generateRsaKey()这三个方法,这些都是JWT签名专属的配置。配置令牌存储
添加TokenStore的Bean,开发阶段可先用内存存储(生产环境建议改用数据库或Redis):@Bean public TokenStore tokenStore() { return new InMemoryTokenStore(); }在认证服务器配置中绑定令牌存储
在授权服务配置类中,将TokenStore注入并关联到端点配置:@Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private TokenStore tokenStore; @Autowired private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("client") .secret("{noop}secret") .authorizedGrantTypes("password", "refresh_token") .scopes("read"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager) .tokenStore(tokenStore); // 绑定令牌存储 } }
修改后的令牌返回示例
配置完成后,/oauth2/token端点会返回不透明格式的访问令牌:
{ "access_token": "78a2d6f4-3b7e-4c5d-8a9b-0e1f2d3c4b5a", "scope": "read", "token_type": "Bearer", "expires_in": 899, "refresh_token": "1b2c3d4e-5f6a-7b8c-9d0e-1f2a3b4c5d6e" }
内容的提问来源于stack exchange,提问作者jhon
相关产品推荐
相关产品推荐

