使用Redis實現(xiàn)JWT令牌主動失效機制
一.實現(xiàn)思路:
- 登錄成功后,給瀏覽器響應(yīng)令牌的同時,把該令牌存儲到Redis中
- LoginInterceptor攔截器中,需要驗證瀏覽器攜帶的令牌,并同時需要獲取到Redis中的存儲的與之相同的令牌,如果獲取到證明令牌有效,如果沒有獲取到則令牌無效
- 當用戶修改密碼成功后,刪除Redis中存儲的舊令牌
二.實現(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: *** #指定使用哪個數(shù)據(jù)源(可不寫,但默認是DB0)(3)編寫配置類,創(chuàng)建RedisTemplate對象:
我們使用RedisTemplate這個類對象內(nèi)封裝的方法來操作Redis,所以我們在配置類內(nèi)創(chuàng)建RedisTemplate并用Bean注解將其交給Spring容器管理。
@Configuration
@Slf4j
public class RedisConfiguration {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
log.info("開始創(chuàng)建Redis模板對象...0");
RedisTemplate redisTemplate = new RedisTemplate();
//設(shè)置redis的連接工廠對象
redisTemplate.setConnectionFactory(redisConnectionFactory);
//設(shè)置redis key的序列化器,這里反應(yīng)的是Redis圖形化工具上value值的不同
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
}2.登錄成功后,給瀏覽器響應(yīng)令牌的同時,把該令牌存儲到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("用戶名錯誤");
}
//判斷密碼是否正確
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存儲到redis中
redisTemplate.opsForValue().set(token,token,1, TimeUnit.HOURS);//key,value,時間值,時間單位
return Result.success(token);
}
return Result.error("密碼錯誤");
}
}3.LoginInterceptor攔截器中,需要驗證瀏覽器攜帶的令牌,并同時需要獲取到Redis中的存儲的與之相同的令牌:
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為請求頭的名字
try {
//從Redis中國獲取相同的token
String redisToken = (String) redisTemplate.opsForValue().get(token);
if(redisToken == null){
//token已經(jīng)失效,拋出異常
throw new RuntimeException();
}
//令牌驗證
Map<String,Object> claims = JwtUtil.parseToken(token);
//線程開辟空間存儲
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.當用戶修改密碼成功后,刪除Redis中存儲的舊令牌:
@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){
//校驗參數(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ù)");
}
//校驗
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中對應(yīng)的token
redisTemplate.opsForValue().getOperations().delete(token);
return Result.success();
}
}到此這篇關(guān)于使用Redis實現(xiàn)JWT令牌主動失效機制的文章就介紹到這了,更多相關(guān)Redis JWT主動失效機制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 如何使用jwt+redis實現(xiàn)單點登錄
- SpringSecurity+Redis+Jwt實現(xiàn)用戶認證授權(quán)
- Shiro整合Springboot和redis,jwt過程中的錯誤shiroFilterChainDefinition問題
- jwt+redis實現(xiàn)登錄認證的示例代碼
- 基于 Redis 的 JWT令牌失效處理方案(實現(xiàn)步驟)
- springboot+springsecurity+mybatis+JWT+Redis?實現(xiàn)前后端離實戰(zhàn)教程
- SpringBoot整合SpringSecurity和JWT和Redis實現(xiàn)統(tǒng)一鑒權(quán)認證
- SpringSecurity+jwt+redis基于數(shù)據(jù)庫登錄認證的實現(xiàn)
- java實現(xiàn)認證與授權(quán)的jwt與token+redis,哪種方案更好用?
相關(guān)文章
Redis簡單動態(tài)字符串SDS的實現(xiàn)示例
Redis沒有直接復(fù)用C語言的字符串,而是新建了SDS,本文主要介紹了Redis簡單動態(tài)字符串SDS的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下2023-08-08
Redis?HyperLogLog數(shù)據(jù)統(tǒng)計輕量級解決方案詳解
這篇文章主要為大家介紹了Redis?HyperLogLog數(shù)據(jù)統(tǒng)計輕量級解決方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12
Redis+Caffeine實現(xiàn)高效兩級緩存架構(gòu)的詳細指南
在現(xiàn)代高并發(fā)系統(tǒng)中,緩存是提升系統(tǒng)性能的關(guān)鍵組件之一,本文將介紹如何結(jié)合 Redis 和 Caffeine 構(gòu)建一個高效的兩級緩存系統(tǒng),需要的小伙伴可以了解下2025-07-07
關(guān)于redis Key淘汰策略的實現(xiàn)方法
下面小編就為大家?guī)硪黄P(guān)于redis Key淘汰策略的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03

