介绍
在这一章节中。 https://blog.csdn.net/baidu_34389984/article/details/85249733 实现了简单的oauth2服务。返回的token是oauth2自生成的token。但有时候,我们希望能在token中加些参数,这时候我们可以用jwt生成token。关于什么是jwt的概念,笔者给出一份资料。https://baijiahao.baidu.com/s?id=1608021814182894637&wfr=spider&for=pc
实现功能
结合jwt+oauth2。返回基于jwt的token。
开发步骤
引用jar包
jar不用引入。oauth2包自导有jwt包。
认证服务器
在之前的认证服务器MyAuthorizationServerConfig类上,添加jwt的配置,并且在jwt中添加用户主键uin。配置如下:
/**
* 定义jwt的生成方式
*
* @return JwtAccessTokenConverter
*/
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter() {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
final Map<String, Object> additionalInformation = new HashMap<>();
UserModel userModel = (UserModel) authentication.getUserAuthentication().getPrincipal();
//把用户的主键uin放进去
additionalInformation.put("uin", userModel.getUin());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
return super.enhance(accessToken, authentication);
}
};
//非对称加密,但jwt长度过长
// KeyPair keyPair = new KeyStoreKeyFactory(new ClassPathResource("kevin_key.jks"), "123456".toCharArray())
// .getKeyPair("kevin_key");
// converter.setKeyPair(keyPair);
// return converter;
//对称加密
converter.setSigningKey("123");
return converter;
}
/**
* 定义授权和令牌端点以及令牌服务
*
* @param endpoints defines the authorization and token endpoints and the token services.
* @throws Exception exception
*/
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
//指定认证管理器
.authenticationManager(authenticationManager)
//用户账号密码认证
.userDetailsService(userDetailsService)
// refresh_token
.reuseRefreshTokens(false)
//指定token存储位置
.tokenStore(tokenStore())
// 配置JwtAccessToken转换器
.accessTokenConverter(accessTokenConverter());
}
首先就是定义JWT的生成方式。然后在endpoints上添加自己的JwtAccessToken转换器。
测试
关于如何访问,请参照上一章节的测试。这里直接给出得到token的结果:
把拿到的jwt放到网站上解除来如下:
项目源码
https://gitee.com/lvhaibao/spring-lhbauth/tree/13b4e27357411de0c8a81ba1397f87e1a32919c7/