redis存储token
redis存储token
欢迎关注博主公众号「Java大师」, 专注于分享Java领域干货文章http://www.javaman.cn/sb2/redis-token
在实际开发中,token需要保存在redis中,今天我们就来介绍下token怎么存储在redis中
密码模式实现代码
2.1 创建pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.6.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.dashi</groupId><artifactId>springsecurity-oauth</artifactId><version>0.0.1-SNAPSHOT</version><name>springsecurity-oauth</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version><spring-cloud.version>Greenwich.SR2</spring-cloud.version></properties><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId><version>2.2.5.RELEASE</version></dependency><!--security依赖--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-security</artifactId><version>2.2.5.RELEASE</version></dependency><!--boot依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><!--boot依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--test依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--redis依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--commons-pool2对象依赖 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>
</project>
2.2 创建springsecurity配置文件
package com.dashi.springsecurityoauth.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}@Beanpublic AuthenticationManager authenticationManager() throws Exception {return super.authenticationManager();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/oauth/**","/login/**","/logout/**").permitAll().anyRequest().authenticated().and().formLogin().permitAll();}
}
2.3 创建UserService实现UserDetailService接口
package com.dashi.springsecurityoauth.model;import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;import java.util.Collection;
import java.util.List;public class User implements UserDetails {private String username;private String password;private List<GrantedAuthority> authorities;public User(String username, String password, List<GrantedAuthority> authorities) {this.username = username;this.password = password;this.authorities = authorities;}@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {return this.authorities;}@Overridepublic String getPassword() {return this.password;}@Overridepublic String getUsername() {return this.username;}@Overridepublic boolean isAccountNonExpired() {return true;}@Overridepublic boolean isAccountNonLocked() {return true;}@Overridepublic boolean isCredentialsNonExpired() {return true;}@Overridepublic boolean isEnabled() {return true;}
}
2.4 创建redis配置
package com.dashi.springsecurityoauth.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;@Configuration
public class RedisConfig {@Autowiredprivate RedisConnectionFactory redisConnectionFactory;@Beanpublic TokenStore redisTokenStore(){return new RedisTokenStore(redisConnectionFactory);}
}
2.5 application.properties配置文件修改
spring.redis.host=localhost
2.6 创建认证服务
package com.dashi.springsecurityoauth.config;import com.dashi.springsecurityoauth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate UserService userService;@Autowired@Qualifier("redisTokenStore")private TokenStore tokenStore;/*** 密码模式采用AuthorizationServerEndpointsConfigurer配置* @param endpoints* @throws Exception*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.authenticationManager(authenticationManager).userDetailsService(userService)//token存储.tokenStore(tokenStore);}/*** 授权码模式采用ClientDetailsServiceConfigurer* @param clients* @throws Exception*/@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("admin").secret(passwordEncoder.encode("112233")).accessTokenValiditySeconds(3600).redirectUris("http://www.baidu.com").scopes("all")//配置grant_type,表示授权码授权//.authorizedGrantTypes("authorization_code");//密码模式.authorizedGrantTypes("password");}
}
2.7 创建资源服务
package com.dashi.springsecurityoauth.config;import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {@Overridepublic void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().requestMatchers()//以/user开头的地址根据token访问资源.antMatchers("/user/**");}
}
2.8 打开postman,填入下面内容获取token
2.9 通过token访问授保护的资源
2.8 redis存储,通过RDM发现token已经存储在redis中了
redis存储token相关推荐
- java redis tokenid_基于Spring及Redis的Token鉴权
为什么用 Token 一般来说都是用 session 来存储登录信息的,但是移动端使用 session 不太方便,所以一般都用 token .另外现在前后端分离,一般都用 token 来鉴权.用 to ...
- 搭建企业级微信公众号管理平台(三)----注册码实现与校验,Redis存储
1.统一接口返回结果集格式 接口应用 /*** 功能说明: 获取微信服务接口*/@ApiOperation(value = "微信应用服务接口")@GetMapping(" ...
- ssh,ssm整合redis存储验证码
ssh整合redis存储验证码 SSM整合redis存储验证码 思路 **获取验证码部分:** **登录部分** 细节 详细代码 前端 后端 SSH 思路: 测试redis是否连接成功 详细代码 后端 ...
- 使用redis存储对象,取对象时的一些常见异常
自动装配失败报空指针异常 报错: java.lang.NullPointerExceptionat com.example.service.UserServiceImpl.sendMsg(UserSe ...
- 每秒1w+分布式事务--dtm的Redis存储性能测试分析
概述 之前dtm给出了Mysql作为存储引擎的性能测试报告,在一个普通配置的机器上,2.68w IOPS,4核8G机器上,能够支持大约每秒900+分布式事务,能够满足大部分公司的业务需求. 此次带来的 ...
- Redis存储总是心里没底?你大概漏了这些数据结构原理
上一篇文章<Redis存储总用String?你大概错过了更优的使用方法>我们了解了Redis的数据类型特点与适用场景,本期内容则会着重讲讲Redis内存数据结构与编码,弄清Redis内部到 ...
- 阿里云短信验证解决方案(java版)(redis存储)
阿里云短信验证解决方案(java版)(redis存储) 参考文章: (1)阿里云短信验证解决方案(java版)(redis存储) (2)https://www.cnblogs.com/Amos-Tur ...
- 大容量类 Redis 存储的场景补充-pika
2019独角兽企业重金招聘Python工程师标准>>> 导读 我们在<大容量类 Redis 存储 - 有关 pika 的一切>里介绍过pika的诞生.pika的特点.pi ...
- Redis 存储字符串和对象
今天用redis存储,发现客户端jedis提供的存储方法中存储的类型只有String和byte数据,没有能够存储对象的,网上发现可以序列化存储对象.这就开始了我第一次序列化之旅. 1 测试类 impo ...
最新文章
- CODING 最佳实践:快课网研发效能提升之路
- 线性表的动态顺序存储和实现(C语言实现)【线性表】(4)
- Eclipse 各版本版本号代号对应一览表
- 25、sql分析命令explain和desc
- 【opencv学习】【模板匹配】
- 基于JAVA+SpringMVC+Mybatis+MYSQL的车库管理系统
- php判断浏览器和语言
- html5 js实现ppt制作,impress.js前端制作酷炫ppt详细教程
- 论文笔记:DCRNN (Diffusion Convolutional Recurrent Neural Network: Data-Driven Traffic Forecasting)
- 国家示范性高职院校名单(109所)
- 2019年了桌面CPU还吊打笔记本CPU?真相了
- xmind打不开java_xmind打开出错(JVM terminated. Exit code=-1) | 学步园
- HCNA网络技术基础学习
- 文档服务器备份策略,服务器备份策略
- Poco脚本的点击位置与点击偏移
- SQL注入攻击及危害
- 如何修改Github仓库的description
- 如何在uni-app中选择一个合适的UI组件库
- 你知道什么是自带PLC的网关吗?
- C语言名题精选百则——数字问题
热门文章
- java第一行输出1当i=10 输出0_当输出模式位MODE[1:0]=10时,最大输出速度为:
- C#编程规范(常用版)
- Hello Metro:Windows 8下首个App
- 中国双目立体显微镜市场趋势报告、技术动态创新及市场预测
- Python机器学习:数据科学,机器学习和人工智能的主要发展技术趋势概述
- PHP火车购票系统,PHPC6051 火车售票系统
- 海外优秀资讯抢先看10:世界著名软件缺陷导致的灾难性案例详解之阿丽安娜火箭之殇
- 宁夏服务器主机性能,宁夏服务器主机
- pymysql插入数据却一直提示right syntax to use near \
- oracle 图表工具,一款简单、实时、酷炫的图表制作软件