SpringBoot OAuth2.0 刷新令牌
通常在 access_token 时间过期后,需要去获取新的 token 才能继续访问接口
在 使用 SpringSecurity + OAuth2.0, 可以采用 refresh_token 模式重新申请 access_token
修改 MooseAuthorizationServerConfiguration 文件
/**
* Authorization Server endpoints.
*
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenGranter(tokenGranter(endpoints))
.tokenStore(tokenStore())
.exceptionTranslator(customOAuth2ResponseExceptionTranslator);
// 用于支持密码模式
endpoints.authenticationManager(authenticationManager);
// 刷新令牌必须添加上,不添加报错 "UserDetailsService is required."
// userDetailsService refresh_token
endpoints.userDetailsService(userDetailsService);
}
修改 oauth_client_details 表
authorized_grant_types 字段添加上 refresh_token 类型,不添加报错 “Unauthorized grant type: refresh_token”
测试
先访问获取 access_token 令牌
http://localhost:7000/oauth/token?password=123456&username=江景&grant_type=password&client_id=client&client_secret=secret
那获取到的 access_token 去刷新令牌,获取到最新的 access_token 和 refresh_token
http://localhost:7000/oauth/token?grant_type=refresh_token&refresh_token=f6c882b8-d9e1-43c3-b41d-291b335775d9&client_id=client&client_secret=secret
最新的 access_token 访问需要授权的接口
如果拿 第 1 步
中的 access_token,访问接口,这个时候是不能访问的,已经被 refresh_token 刷新调了。
关注公众号 「全栈技术部」
,不断学习更多有趣的技术知识。
