Spring Cloud Security 为构建安全的SpringBoot应用提供了一系列解决方案,结合Oauth2还可以实现更多功能,比如使用JWT令牌存储信息,刷新令牌功能,本文将对其结合JWT使用进行详细介绍。

JWT简介

JWT是JSON WEB TOKEN的缩写,它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象,由于使用了数字签名,所以是可信任和安全的。

JWT的组成

  • JWT token的格式:header.payload.signature;
  • header中用于存放签名的生成算法;
{"alg": "HS256","typ": "JWT"}
  • payload中用于存放数据,比如过期时间、用户名、用户所拥有的权限等;
{"exp": 1572682831,"user_name": "macro","authorities": ["admin"  ],"jti": "c1a0645a-28b5-4468-b4c7-9623131853af","client_id": "admin","scope": ["all"  ]}
  • signature为以header和payload生成的签名,一旦header和payload被篡改,验证将失败。

JWT实例

  • 这是一个JWT的字符串:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzI2ODI4MzEsInVzZXJfbmFtZSI6Im1hY3JvIiwiYXV0aG9yaXRpZXMiOlsiYWRtaW4iXSwianRpIjoiYzFhMDY0NWEtMjhiNS00NDY4LWI0YzctOTYyMzEzMTg1M2FmIiwiY2xpZW50X2lkIjoiYWRtaW4iLCJzY29wZSI6WyJhbGwiXX0.x4i6sRN49R6JSjd5hd1Fr2DdEMBsYdC4KB6Uw1huXPg
  • 可以在该网站上获得解析结果:https://jwt.io/

创建oauth2-jwt-server模块

该模块只是对oauth2-server模块的扩展,直接复制过来扩展下下即可。

oauth2中存储令牌的方式

在上一节中我们都是把令牌存储在内存中的,这样如果部署多个服务,就会导致无法使用令牌的问题。Spring Cloud Security中有两种存储令牌的方式可用于解决该问题,一种是使用Redis来存储,另一种是使用JWT来存储。

使用Redis存储令牌

  • 在pom.xml中添加Redis相关依赖:
<dependency><groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-data-redisartifactId>dependency>
  • 在application.yml中添加redis相关配置:
spring:  redis: #redis相关配置    password: 123456 #有密码时设置
  • 添加在Redis中存储令牌的配置:
/** * 使用redis存储token的配置 * Created by macro on 2019/10/8. */@Configurationpublic class RedisTokenStoreConfig {

@Autowiredprivate RedisConnectionFactory redisConnectionFactory;

@Beanpublic TokenStore redisTokenStore (){return new RedisTokenStore(redisConnectionFactory);    }}
  • 在认证服务器配置中指定令牌的存储策略为Redis:
/** * 认证服务器配置 * Created by macro on 2019/9/30. */@Configuration@EnableAuthorizationServerpublic class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowiredprivate PasswordEncoder passwordEncoder;

@Autowiredprivate AuthenticationManager authenticationManager;

@Autowiredprivate UserService userService;

@Autowired@Qualifier("redisTokenStore")private TokenStore tokenStore;

/**     * 使用密码模式需要配置     */@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {        endpoints.authenticationManager(authenticationManager)                .userDetailsService(userService)                .tokenStore(tokenStore);//配置令牌存储策略    }

//省略代码...}
  • 运行项目后使用密码模式来获取令牌,访问如下地址:http://localhost:9401/oauth/token

  • 进行获取令牌操作,可以发现令牌已经被存储到Redis中。

使用JWT存储令牌

  • 添加使用JWT存储令牌的配置:
/** * 使用Jwt存储token的配置 * Created by macro on 2019/10/8. */@Configurationpublic class JwtTokenStoreConfig {

@Beanpublic TokenStore jwtTokenStore() {return new JwtTokenStore(jwtAccessTokenConverter());    }

@Beanpublic JwtAccessTokenConverter jwtAccessTokenConverter() {        JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();        accessTokenConverter.setSigningKey("test_key");//配置JWT使用的秘钥return accessTokenConverter;    }}
  • 在认证服务器配置中指定令牌的存储策略为JWT:
/** * 认证服务器配置 * Created by macro on 2019/9/30. */@Configuration@EnableAuthorizationServerpublic class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowiredprivate PasswordEncoder passwordEncoder;

@Autowiredprivate AuthenticationManager authenticationManager;

@Autowiredprivate UserService userService;

@Autowired@Qualifier("jwtTokenStore")private TokenStore tokenStore;@Autowiredprivate JwtAccessTokenConverter jwtAccessTokenConverter;@Autowiredprivate JwtTokenEnhancer jwtTokenEnhancer;

/**     * 使用密码模式需要配置     */@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {        endpoints.authenticationManager(authenticationManager)                .userDetailsService(userService)                .tokenStore(tokenStore) //配置令牌存储策略                .accessTokenConverter(jwtAccessTokenConverter);    }

//省略代码...}
  • 运行项目后使用密码模式来获取令牌,访问如下地址:http://localhost:9401/oauth/token

  • 发现获取到的令牌已经变成了JWT令牌,将access_token拿到https://jwt.io/ 网站上去解析下可以获得其中内容。
{"exp": 1572682831,"user_name": "macro","authorities": ["admin"  ],"jti": "c1a0645a-28b5-4468-b4c7-9623131853af","client_id": "admin","scope": ["all"  ]}

扩展JWT中存储的内容

有时候我们需要扩展JWT中存储的内容,这里我们在JWT中扩展一个key为enhance,value为enhance info的数据。

  • 继承TokenEnhancer实现一个JWT内容增强器:
/** * Jwt内容增强器 * Created by macro on 2019/10/8. */public class JwtTokenEnhancer implements TokenEnhancer {@Overridepublic OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {        Map info = new HashMap<>();        info.put("enhance", "enhance info");        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);return accessToken;    }}
  • 创建一个JwtTokenEnhancer实例:
/** * 使用Jwt存储token的配置 * Created by macro on 2019/10/8. */@Configurationpublic class JwtTokenStoreConfig {

//省略代码...

@Beanpublic JwtTokenEnhancer jwtTokenEnhancer() {return new JwtTokenEnhancer();    }}
  • 在认证服务器配置中配置JWT的内容增强器:
/** * 认证服务器配置 * Created by macro on 2019/9/30. */@Configuration@EnableAuthorizationServerpublic class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowiredprivate PasswordEncoder passwordEncoder;

@Autowiredprivate AuthenticationManager authenticationManager;

@Autowiredprivate UserService userService;

@Autowired@Qualifier("jwtTokenStore")private TokenStore tokenStore;@Autowiredprivate JwtAccessTokenConverter jwtAccessTokenConverter;@Autowiredprivate JwtTokenEnhancer jwtTokenEnhancer;

/**     * 使用密码模式需要配置     */@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) {        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();        List delegates = new ArrayList<>();        delegates.add(jwtTokenEnhancer); //配置JWT的内容增强器        delegates.add(jwtAccessTokenConverter);        enhancerChain.setTokenEnhancers(delegates);        endpoints.authenticationManager(authenticationManager)                .userDetailsService(userService)                .tokenStore(tokenStore) //配置令牌存储策略                .accessTokenConverter(jwtAccessTokenConverter)                .tokenEnhancer(enhancerChain);    }//省略代码...}
  • 运行项目后使用密码模式来获取令牌,之后对令牌进行解析,发现已经包含扩展的内容。
{"user_name": "macro","scope": ["all"  ],"exp": 1572683821,"authorities": ["admin"  ],"jti": "1ed1b0d8-f4ea-45a7-8375-211001a51a9e","client_id": "admin","enhance": "enhance info"}

Java中解析JWT中的内容

如果我们需要获取JWT中的信息,可以使用一个叫jjwt的工具包。

  • 在pom.xml中添加相关依赖:
<dependency><groupId>io.jsonwebtokengroupId><artifactId>jjwtartifactId><version>0.9.0version>dependency>
  • 修改UserController类,使用jjwt工具类来解析Authorization头中存储的JWT内容。
/** * Created by macro on 2019/9/30. */@RestController@RequestMapping("/user")public class UserController {@GetMapping("/getCurrentUser")public Object getCurrentUser(Authentication authentication, HttpServletRequest request) {        String header = request.getHeader("Authorization");        String token = StrUtil.subAfter(header, "bearer ", false);return Jwts.parser()                .setSigningKey("test_key".getBytes(StandardCharsets.UTF_8))                .parseClaimsJws(token)                .getBody();    }

}
  • 将令牌放入Authorization头中,访问如下地址获取信息:http://localhost:9401/user/getCurrentUser

刷新令牌

在Spring Cloud Security 中使用oauth2时,如果令牌失效了,可以使用刷新令牌通过refresh_token的授权模式再次获取access_token。

  • 只需修改认证服务器的配置,添加refresh_token的授权模式即可。
/** * 认证服务器配置 * Created by macro on 2019/9/30. */@Configuration@EnableAuthorizationServerpublic class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {        clients.inMemory()                .withClient("admin")                .secret(passwordEncoder.encode("admin123456"))                .accessTokenValiditySeconds(3600)                .refreshTokenValiditySeconds(864000)                .redirectUris("http://www.baidu.com")                .autoApprove(true) //自动授权配置                .scopes("all")                .authorizedGrantTypes("authorization_code","password","refresh_token"); //添加授权模式    }}
  • 使用刷新令牌模式来获取新的令牌,访问如下地址:http://localhost:9401/oauth/token

使用到的模块

springcloud-learning└── oauth2-jwt-server -- 使用jwt的oauth2认证测试服务

项目源码地址

https://github.com/macrozheng/springcloud-learning

推荐阅读

  • 不就是SELECT COUNT语句吗,居然有这么多学问!
  • 这样讲API网关,你应该能明白了吧!
  • 使用策略+工厂模式彻底干掉代码中的if else!
  • 后端程序员必备:Mysql数据库相关流程图/原理图
  • 我的Github开源项目,从0到20000 Star!
  • Spring Cloud Security:Oauth2使用入门
  • Spring Boot Admin:微服务应用监控
  • Spring Cloud Gateway:新一代API网关服务
  • Spring Cloud Consul:服务治理与配置中心
  • Spring Cloud Sleuth:分布式请求链路跟踪
  • Spring Cloud Bus:消息总线
  • Spring Cloud Config:外部集中化配置管理

欢迎关注,点个在看

jwt需要存redis吗_Spring Cloud Security:Oauth2结合JWT使用相关推荐

  1. gateway oauth2 对称加密_深入理解Spring Cloud Security OAuth2及JWT

    因项目需要,需要和三方的oauth2服务器进行集成.网上关于spring cloud security oauth2的相关资料,一般都是讲如何配置,而能把这块原理讲透彻的比较少,这边自己做一下总结和整 ...

  2. 《深入理解 Spring Cloud 与微服务构建》第十八章 使用 Spring Security OAuth2 和 JWT 保护微服务系统

    <深入理解 Spring Cloud 与微服务构建>第十八章 使用 Spring Security OAuth2 和 JWT 保护微服务系统 文章目录 <深入理解 Spring Cl ...

  3. 基于 Spring Security OAuth2和 JWT 构建保护微服务系统

    我们希望自己的微服务能够在用户登录之后才可以访问,而单独给每个微服务单独做用户权限模块就显得很弱了,从复用角度来说是需要重构的,从功能角度来说,也是欠缺的.尤其是前后端完全分离之后,我们的用户信息不一 ...

  4. Spring Security OAuth2整合JWT

    文章目录 1. Spring Security 与 OAuth2 2. Spring Security OAuth2的配置和使用 ①:引入依赖 ②:配置 spring security ③:配置授权服 ...

  5. 【java_wxid项目】【第七章】【Spring Cloud Security Oauth2集成】

    主项目链接:https://gitee.com/java_wxid/java_wxid 项目架构及博文总结: 点击:[使用Spring Boot快速构建应用] 点击:[使用Spring Cloud O ...

  6. 玩转Spring Cloud Security OAuth2身份认证扩展——电话号码+验证码认证

    在程序的认证过程中,除了常规的用户名和密码方式(可以参考深入理解Spring Cloud Security OAuth2身份认证),也经常会出现电话号码+密码的方式:电话号码+验证码的方式:或者第三方 ...

  7. JWT实战 Spring Security Oauth2整合JWT 整合SSO单点登录

    文章目录 一.JWT 1.1 什么是JWT 1.2 JWT组成 头部(header) 载荷(payload) 签名(signature) 如何应用 1.3 JJWT 快速开始 创建token toke ...

  8. 使用Spring Security Oauth2 和 JWT保护微服务--Uaa授权服务器的编写

    学习自深入理解微服务 采用Spring Security OAuth2 和 JWT的方式,Uaa服务只需要验证一次,返回JWT.返回的JWT包含了用户的所有信息,包括权限信息 从三个方面讲解: JWT ...

  9. 使用Spring Security Oauth2 和 JWT保护微服务--资源服务器的编写

    编写hcnet-website的资源服务 依赖管理pom文件 hcnet-website工程的pom文件继承主maven的pom文件.在hcnet-website工程的pom文件中添加web功能的起步 ...

最新文章

  1. python中rename函数_python os.rename(…)不起作用!
  2. PHP-7.1 源代码学习:字节码在 Zend 虚拟机中的解释执行 之 概述
  3. 猎鹰spacex_SpaceX:简单,美观的界面是未来
  4. ASP.NET MVC3 Action Filters详解(一)
  5. Liferay Portal使用MySQL数据库配置
  6. 列表推导式 生成器表达式
  7. MVC下c#对接微信公众平台开发者模式
  8. c#自带类实现的多文件压缩和解压
  9. 2021年5月软考网络工程师上午真题(带答案解析)上
  10. 校园网\中心机房\拓扑图 思科模拟器(cisco)
  11. 建行u盾弹不出来_安装建行的网银盾驱动的时候系统检测不出怎么办
  12. 百度统计后台页面点击图提示无法建立连接
  13. 二进制如何转十进制,十进制如何转二进制
  14. 4103 yxc 的日常
  15. 长连接-心跳保活机制
  16. 京东商城商品分类列表页面
  17. cadence virtuoso前仿出现模型缺失
  18. 数据库应用+SQL优化+Git
  19. Windows 任意窗口置顶显示
  20. cwl的网络流24题练习

热门文章

  1. 【leetcode238】Product of Array Except Self
  2. Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.107.el6.i686
  3. Rust即将发布1.0版本,Go持续获得关注:如何在新生语言之间做出抉择
  4. (多图) 基于Verilog HDL的FIR数字滤波器设计与仿真
  5. 笔记本电脑双显卡的切换技巧
  6. js获取已知scripts中是否存在某变量_JS全局变量是如何工作的?
  7. python任务队列 http_基于Python开发的分布式任务队列:Celery
  8. mysql 5.7_MySQL 5.7新特性介绍
  9. scala mysql bit_Scala连接mysql数据库
  10. 如何制作一颗CPU? 从石子到管脚绑定