当前位置:网站首页>Project practice 4: user login and token access verification (reids+jwt)
Project practice 4: user login and token access verification (reids+jwt)
2022-06-26 18:33:00 【cc_ nanke dream】
1、 Registry Center , Configuration center , gateway ,Feign You can refer to the following articles
【1】:nacos:https://blog.csdn.net/qq_28326501/article/details/117822745
【2】: gateway :https://blog.csdn.net/qq_28326501/article/details/118225407
【3】:Feign:https://blog.csdn.net/qq_28326501/article/details/118440999
【4】:redis:https://blog.csdn.net/qq_28326501/article/details/118346062
2: Overall structure and description of the project
Log in through jwt Generate token Back to the front end , meanwhile token use redis Control expiration . Other requests need to be made in header put token. Use fegin The filter shall be uniformly verified .

3、 Log in to get token
The main method :
【1】:service Method :
/**
* obtain token
* @author cc
* @date 2021/6/30 22:35
* @param dto
* @return com.cc.common.vo.ReturnVo
*/
@Override
public ReturnVo login(UserDto dto) {
// Determine whether the user name and password are correct
Boolean b = getUser(dto);
// Generate correctly token return // Error return prompt
if(b){
// Generate token
String token = TokenUtil.getToken(dto.getName());
//token Put in redis, use redis Controls whether to expire and refresh
boolean rs = redisUtil.set("cc" + dto.getName(), token, 300);
if (rs){
return ReturnVoUtil.success(" Login successful ", token);
}else{
return ReturnVoUtil.error(" Login failed ");
}
}else{
return ReturnVoUtil.error(" Wrong user name or password ");
}
}【2】:token Tool class
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.12.1</version>
</dependency>package com.cc.oauth.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.HashMap;
import java.util.Map;
/**
* @author cc
* @data 2021 year 06 month 28 Japan 23:34
*/
public class TokenUtil {
// Custom key
private static String secretKey = "mysecret";
// Issuer
private static String CC_KEY = "cc_jwt_token";
/**
* Generate signature
* @author cc
* @date 2021/6/28 23:35
*/
public static String getToken(String userName){
// To get the key
Algorithm algorithm = getAlgorithm();
// Add custom information
Map map = new HashMap();
map.put("userName", userName);
// Set up keyId
String keyId = "cc"+userName;
String token = JWT.create()
//.withIssuedAt(now)// current time
//.withExpiresAt(expiresDate)// Expiration time
.withKeyId(keyId)
.withIssuer(CC_KEY)// Issuer
.withHeader(map)// Custom information
.sign(algorithm);// secret key
return token;
}
/**
* Resolve signature
* @author cc
* @date 2021/6/28 23:35
*/
public static String parseToken(String token){
String msg = null;
// To get the key
Algorithm algorithm = getAlgorithm();
JWTVerifier jwtVerifier = JWT.require(algorithm)
.withIssuer(CC_KEY)// Issuer
.build();
DecodedJWT jwt = jwtVerifier.verify(token);
String userName = jwt.getHeaderClaim("userName").as(String.class);
return userName;
}
/**
* Get a custom key
* @author cc
* @date 2021/6/29 17:01
*/
private static Algorithm getAlgorithm(){
Algorithm algorithm = Algorithm.HMAC256(secretKey);
return algorithm;
}
}
【3】:Controller Method
/**
* Log in to get token
* @author cc
* @date 2021/6/30 22:31
* @param dto
* @return com.cc.common.vo.ReturnVo
*/
@RequestMapping("/login")
public ReturnVo login(@RequestBody @Validated({Set.class, List.class}) UserDto dto){
ReturnVo login = loginService.login(dto);
return login;
}4、token Checksum gateway filter
【1】:LoginFiter
package com.cc.gateway.filter;
import com.cc.common.dto.UserDto;
import com.cc.common.utils.JSONUtils;
import com.cc.common.utils.ReturnVoUtil;
import com.cc.common.vo.ReturnVo;
import com.cc.gateway.feign.OauthFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;
/**
* visit token Verify filter
* @author cc
* @data 2021 year 06 month 30 Japan 17:47
*/
@Component
public class LoginFilter implements GlobalFilter, Ordered {
@Autowired
private OauthFeign oauthFeign;
@Value("${mysettings.skip-url}")
private List<String> skipUrl;
/**
* The core approach
* @author cc
* @date 2021/6/30 17:50
* @param exchange
* @param chain
* @return reactor.core.publisher.Mono<java.lang.Void>
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// Take... Out of context request and response object
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
// Get request url
String url = request.getURI().getPath();
url = url.substring(4,url.length());
// Determine whether not to verify token Direct release
boolean contains = skipUrl.contains(url);
if(contains){
// yes , Direct release
return chain.filter(exchange);
}else{
// In the request header token Conduct token verification
List<String> tokens = request.getHeaders().get("token");
ReturnVo<Boolean> vo = ReturnVoUtil.error(" Please log in ", false);
String token = null;
if(tokens != null){
token = tokens.get(0);
UserDto dto = new UserDto();
dto.setToken(token);
//token verification
vo = oauthFeign.checkToken(dto);
}
if(vo.getData()){
// token correct , Refresh redis Expiration time , Simultaneous release ⾏
return chain.filter(exchange);
}else{
//token error
response.setStatusCode(HttpStatus.UNAUTHORIZED);// Status code
String s = JSONUtils.beanToJson(vo);
DataBuffer wrap = response.bufferFactory().wrap(s.getBytes());
return response.writeWith(Mono.just(wrap));
}
}
}
@Override
public int getOrder() {
return 1;
}
}
【2】:token Verification method
/**
* Check token Whether it is right
* @author cc
* @date 2021/6/30 22:35
* @return com.cc.common.vo.ReturnVo
*/
public ReturnVo checkToken(String token){
try{
// analysis token Get user name
String user = TokenUtil.parseToken(token);
// according to username from redis To see if there is such keytoken
String rtoken = (String) redisUtil.get("cc" + user);
if (StringUtils.isEmpty(rtoken)){
return ReturnVoUtil.success("token Overtime , Please log in ",false);
}
if (token.equals(rtoken)){
return ReturnVoUtil.success("token correct ",true);
}else{
return ReturnVoUtil.success("token error , Please log in ",false);
}
}catch (Exception e){
e.printStackTrace();
return ReturnVoUtil.error("token error , Please log in ",false);
}
}
5、 Request example
Log in to get token

Yes token

nothing token

边栏推荐
- Reading notes: process consulting III
- Map and filter methods for processing scarce arrays
- (multi threading knowledge points that must be mastered) understand threads, create threads, common methods and properties of using threads, and the meaning of thread state and state transition
- JVM入个门(1)
- To: seek truth from facts
- Boyun, standing at the forefront of China's container industry
- 博云,站在中国容器潮头
- Leetcode 238 product of arrays other than itself
- JVM entry door (1)
- sql 中的alter操作总结
猜你喜欢
随机推荐
成功解决之idea引用Lombok的@Slf4j后无法正常使用log
[kubernetes] kubernetes principle analysis and practical application (under update)
Class inheritance of 25class
(几何) 凸包问题
ISO文件
一些基本错误
xlua获取ugui的button注册click事件
判断某个序列是否为栈的弹出序列
8VC Venture Cup 2017 - Final Round C. Nikita and stack
爬取豆瓣读书Top250,导入sqlist数据库(或excel表格)中
To: seek truth from facts
必须要掌握的面试重点——索引和事务(附讲B-树与B+树)
The cross compilation environment appears So link file not found problem
刷新三观的HP-UX系统中的强指针赋值出core问题
Idea collection code, quickly open favorites collection window
JVM entry Door (1)
成功解决之Jenkins报错:The goal you specified requires a project to execute but there is no POM
【Kubernetes】Kubernetes 原理剖析与实战应用(更新中)
Record of user behavior log in SSO microservice Engineering
Determine whether a sequence is a stack pop-up sequence









