当前位置:网站首页>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

边栏推荐
- Boyun, standing at the forefront of China's container industry
- Handwritten promise all
- Deep learning: numpy
- CD-CompactDisk
- Yujun product methodology
- ROS query topic specific content common instructions
- 字符串String转换为jsonArray并解析
- JVM entry door (1)
- Conditional compilation in precompiling instructions
- SQL中的并、交、差运算
猜你喜欢
随机推荐
Vscode 基础必备 常用插件
Résumé des points de connaissance
带你解决哈希冲突,并实现一个简单hash表,
限流设计及实现
Ethereum技术架构介绍
Comparing the size relationship between two objects turns out to be so fancy
Tag dynamic programming - preliminary knowledge for question brushing -2 0-1 knapsack theory foundation and two-dimensional array solution template
Leetcode interview question 29 clockwise print matrix
Handwritten promise all
Determine whether a sequence is a stack pop-up sequence
Soft test preparation multimedia system
新手炒股开户选哪个证券公司比较好?怎样炒股比较安全??
ROS的发布消息Publishers和订阅消息Subscribers
CLion断点单步调试
元宇宙链游开发案例版 NFT元宇宙链游系统开发技术分析
Example of using QPushButton style (and method of adding drop-down menu to button SetMenu)
Leetcode 238 product of arrays other than itself
MySQL download and configuration MySQL remote control
How to create and enforce indexes
输入n个整数,输出出现次数大于等于数组长度一半的数









