使用Redis實(shí)現(xiàn)JWT令牌主動(dòng)失效機(jī)制
一.實(shí)現(xiàn)思路:
- 登錄成功后,給瀏覽器響應(yīng)令牌的同時(shí),把該令牌存儲(chǔ)到Redis中
- LoginInterceptor攔截器中,需要驗(yàn)證瀏覽器攜帶的令牌,并同時(shí)需要獲取到Redis中的存儲(chǔ)的與之相同的令牌,如果獲取到證明令牌有效,如果沒有獲取到則令牌無效
- 當(dāng)用戶修改密碼成功后,刪除Redis中存儲(chǔ)的舊令牌
二.實(shí)現(xiàn)代碼解析:
1.首先配置Redis的相關(guān)配置文件:
(1)pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>(2)在application.yml中配置相關(guān)信息:
spring:
data:
redis:
host: localhost
port: 6379
password: ******* #Redis的密碼
database: *** #指定使用哪個(gè)數(shù)據(jù)源(可不寫,但默認(rèn)是DB0)(3)編寫配置類,創(chuàng)建RedisTemplate對(duì)象:
我們使用RedisTemplate這個(gè)類對(duì)象內(nèi)封裝的方法來操作Redis,所以我們?cè)谂渲妙悆?nèi)創(chuàng)建RedisTemplate并用Bean注解將其交給Spring容器管理。
@Configuration
@Slf4j
public class RedisConfiguration {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
log.info("開始創(chuàng)建Redis模板對(duì)象...0");
RedisTemplate redisTemplate = new RedisTemplate();
//設(shè)置redis的連接工廠對(duì)象
redisTemplate.setConnectionFactory(redisConnectionFactory);
//設(shè)置redis key的序列化器,這里反應(yīng)的是Redis圖形化工具上value值的不同
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
}2.登錄成功后,給瀏覽器響應(yīng)令牌的同時(shí),把該令牌存儲(chǔ)到Redis中:
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
@Autowired
private UserService userService;
@Autowired
private RedisTemplate redisTemplate;
/**
* 用戶登錄
* @param username
* @param password
* @return
*/
@PostMapping("/login")
public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username ,@Pattern(regexp = "^\\S{5,16}$") String password){
//根據(jù)username查詢用戶
User loginUser = userService.findByUserName(username);
//判斷是否存在
if(loginUser == null){
return Result.error("用戶名錯(cuò)誤");
}
//判斷密碼是否正確
if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
//登錄成功,創(chuàng)建JWT令牌
Map<String,Object> claims = new HashMap<>();
claims.put("id",loginUser.getId());
claims.put("username",loginUser.getUsername());
String token = JwtUtil.genToken(claims);
//將token存儲(chǔ)到redis中
redisTemplate.opsForValue().set(token,token,1, TimeUnit.HOURS);//key,value,時(shí)間值,時(shí)間單位
return Result.success(token);
}
return Result.error("密碼錯(cuò)誤");
}
}3.LoginInterceptor攔截器中,需要驗(yàn)證瀏覽器攜帶的令牌,并同時(shí)需要獲取到Redis中的存儲(chǔ)的與之相同的令牌:
package com.itheima.bigdealboot.interceptors;
import com.itheima.bigdealboot.utils.JwtUtil;
import com.itheima.bigdealboot.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Map;
//攔截器
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request , HttpServletResponse response , Object handle) throws Exception{
String token = request.getHeader("Authorization"); //Authorization為請(qǐng)求頭的名字
try {
//從Redis中國獲取相同的token
String redisToken = (String) redisTemplate.opsForValue().get(token);
if(redisToken == null){
//token已經(jīng)失效,拋出異常
throw new RuntimeException();
}
//令牌驗(yàn)證
Map<String,Object> claims = JwtUtil.parseToken(token);
//線程開辟空間存儲(chǔ)
ThreadLocalUtil.set(claims);
//放行
return true;
}catch (Exception e){
//http響應(yīng)狀態(tài)碼為401在·
response.setStatus(401);
//不放行
return false;
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//清空線程數(shù)據(jù)
ThreadLocalUtil.remove();
}
}4.當(dāng)用戶修改密碼成功后,刪除Redis中存儲(chǔ)的舊令牌:
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
@Autowired
private UserService userService;
@Autowired
private RedisTemplate redisTemplate;
@PatchMapping("/updatePwd")
public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
//校驗(yàn)參數(shù)
String oldPwd = params.get("old_pwd");
String newPwd = params.get("new_pwd");
String rePwd = params.get("re_pwd");
if(StringUtils.hasLength(oldPwd) || StringUtils.hasLength(newPwd) || StringUtils.hasLength(rePwd)){
return Result.error("缺少必要參數(shù)");
}
//校驗(yàn)
Map<String,Object> map = ThreadLocalUtil.get();
String username = (String) map.get("username");
User loginUser = userService.findByUserName(username);
if(!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
return Result.error("原密碼填寫不正確");
}
if(!rePwd.equals(newPwd)){
return Result.error("兩次填寫的新密碼不一樣");
}
//更新密碼
userService.updatePwd(newPwd);
//刪除redis中對(duì)應(yīng)的token
redisTemplate.opsForValue().getOperations().delete(token);
return Result.success();
}
}到此這篇關(guān)于使用Redis實(shí)現(xiàn)JWT令牌主動(dòng)失效機(jī)制的文章就介紹到這了,更多相關(guān)Redis JWT主動(dòng)失效機(jī)制內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 如何使用jwt+redis實(shí)現(xiàn)單點(diǎn)登錄
- SpringSecurity+Redis+Jwt實(shí)現(xiàn)用戶認(rèn)證授權(quán)
- Shiro整合Springboot和redis,jwt過程中的錯(cuò)誤shiroFilterChainDefinition問題
- jwt+redis實(shí)現(xiàn)登錄認(rèn)證的示例代碼
- 基于 Redis 的 JWT令牌失效處理方案(實(shí)現(xiàn)步驟)
- springboot+springsecurity+mybatis+JWT+Redis?實(shí)現(xiàn)前后端離實(shí)戰(zhàn)教程
- SpringBoot整合SpringSecurity和JWT和Redis實(shí)現(xiàn)統(tǒng)一鑒權(quán)認(rèn)證
- SpringSecurity+jwt+redis基于數(shù)據(jù)庫登錄認(rèn)證的實(shí)現(xiàn)
- java實(shí)現(xiàn)認(rèn)證與授權(quán)的jwt與token+redis,哪種方案更好用?
相關(guān)文章
Redis簡(jiǎn)單動(dòng)態(tài)字符串SDS的實(shí)現(xiàn)示例
Redis沒有直接復(fù)用C語言的字符串,而是新建了SDS,本文主要介紹了Redis簡(jiǎn)單動(dòng)態(tài)字符串SDS的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2023-08-08
Redis?HyperLogLog數(shù)據(jù)統(tǒng)計(jì)輕量級(jí)解決方案詳解
這篇文章主要為大家介紹了Redis?HyperLogLog數(shù)據(jù)統(tǒng)計(jì)輕量級(jí)解決方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Redis+Caffeine實(shí)現(xiàn)高效兩級(jí)緩存架構(gòu)的詳細(xì)指南
在現(xiàn)代高并發(fā)系統(tǒng)中,緩存是提升系統(tǒng)性能的關(guān)鍵組件之一,本文將介紹如何結(jié)合 Redis 和 Caffeine 構(gòu)建一個(gè)高效的兩級(jí)緩存系統(tǒng),需要的小伙伴可以了解下2025-07-07
關(guān)于redis Key淘汰策略的實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄P(guān)于redis Key淘汰策略的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-03-03
redis3.2配置文件redis.conf詳細(xì)說明
redis3.2配置詳解,Redis啟動(dòng)的時(shí)候,可以指定配置文件,詳細(xì)說明請(qǐng)看本文說明2018-03-03

