SpringBoot集成SpringSecurity5和OAuth2 — 5、OAuth2集成JWT

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

关于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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值