关于JWT是什么等有关内容本文不做介绍,只讲解OAuth2如何集成JWT,JWT的加密解密等。
本次代码是在SpringBoot集成SpringSecurity5和OAuth2 — 3、基于数据库的OAuth2认证服务器基础上完成的
一、OAuth2集成JWT
1.1加入 spring-security-jwt依赖
<!-- spring-security-jwt -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>
1.2 新建一个JWT的配置类JwtConfig
package cn.iotspider.oauth2jdbc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
@Configuration
public class JwtConfig {
/**
* 生成具有jwt的token
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
//设置JWT使用签名
// accessTokenConverter.setSigningKey("iot_OAuth2_key");
accessTokenConverter.setSigningKey("29568a368d5eff3ff");
return accessTokenConverter;
}
/**
* token存储在jwt中
*/
@Bean
public TokenStore jwtTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
/**
* 存储了扩展的JWT信息
* @return
*/
@Bean
public Oauth2JwtTokenEnhancer oauth2JwtTokenEnhancer() {
return new Oauth2JwtTokenEnhancer();
}
}
1.3 新建一个Oauth2JwtTokenEnhancer用于扩展JWT中的信息
package cn.iotspider.oauth2jdbc.config;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import java.util.HashMap;
import java.util.Map;
public class Oauth2JwtTokenEnhancer implements TokenEnhancer {
/**
* 扩展JWT中的内容,oAuth2Authentication中存储有登陆成功后的用户信息
* @param oAuth2AccessToken
* @param oAuth2Authentication
* @return
*/
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
Map<String, Obj

本文详细介绍了如何在SpringBoot项目中集成SpringSecurity5和OAuth2,实现JWT的加密解密和存储,包括代码示例和步骤说明。
最低0.47元/天 解锁文章
7996

被折叠的 条评论
为什么被折叠?



