当前位置:网站首页>JWT login authentication
JWT login authentication
2022-06-29 18:18:00 【Math kids who don't like fitness are not good programmers】

Catalog
Two 、 writing tool (config) package
One 、JWT What is it? ?
1. Concept
JWT It's a simple way to transfer security information between two parties 、URL Specification of safety statements . Is the user name 、 Password to login , After server verification , Will generate a token, Return to the client , The client will carry this in the next visit token, The server is responsible for verifying this every time token. Because of the existence of digital signature , This information is credible ,JWT have access to HMAC Algorithm or RSA The public and private key pair of .
2. structure
- header (Header)
- Payload (Payload)
- Signature (Signature)
Two 、 writing tool (config) package
stay SpringBoot Create... Under the project config( tool kit ) package , Create classes and enumerations under the package .
1.JwtUtils
package com.alanx.java.util;
import com.alanx.java.bean.Users;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
public class JwtUtils {
// Constant
public static final long EXPIRE = 1000 * 60 * 60 * 24; //token Expiration time
public static final String APP_SECRET = "13579"; // Secret key , Add salt
// @param id The current user ID
// @param issuer The JWT Issued by , Whether to use is optional
// @param subject The JWT Target users , Whether to use is optional
// @param ttlMillis When does it expire , Here is a Unix Time stamp , Whether to use is optional
// @param audience To receive JWT On the side of , Whether to use is optional
// Generate token String method
public static String getJwtToken(Users user) {
String JwtToken = Jwts.builder()
.setHeaderParam("typ", "JWT") // Header information
.setHeaderParam("alg", "HS256") // Header information
// The next part is payload part
// Set the default label
.setSubject("alanx") // Set up jwt Target users
.setIssuedAt(new Date()) // Set the time when the visa will take effect
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) // Set the expiration date of the visa
// Customized information , It's stored here id And name information
.claim("id", user.getId()) // Set up token Main part , Store user information
.claim("name", user.getUserName())
.claim("nickName",user.getNickName())
// Here's the third part
.signWith(SignatureAlgorithm.HS256, APP_SECRET)
.compact();
// The resulting string is jwt Information , This one usually goes back out
return JwtToken;
}
/**
* Judge token Whether it exists and works
* Directly determine the string form of jwt character string
*
* @param jwtToken
* @return
*/
public static boolean checkToken(String jwtToken) {
if (StringUtils.isEmpty(jwtToken)) return false;
try {
Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Judge token Whether it exists and works
* Because usually jwt It's all carried in the request header , The parameter passed in by this method is request
*
* @param request
* @return
*/
public static boolean checkToken(HttpServletRequest request) {
try {
String jwtToken = request.getHeader("token");// Note that the name must be token To get jwt
if (StringUtils.isEmpty(jwtToken)) return false;
Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* according to token String to get members id
* This method also comes directly from http In the request of id Of
*
* @param request
* @return
*/
public static String getMemberIdByJwtToken(HttpServletRequest request) {
String jwtToken = request.getHeader("token");
if (StringUtils.isEmpty(jwtToken)) return "";
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
Claims claims = claimsJws.getBody();
return (String) claims.get("id");
}
/**
* analysis JWT
*
* @param jwt
* @return
*/
public static Claims parseJWT(String jwt) {
Claims claims = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwt).getBody();
return claims;
}
}
2.JsonResult
package com.alanx.java.util;
import lombok.Data;
import java.io.Serializable;
/**
* @Description: Unified return entity
*/
@Data
public class JsonResult<T> implements Serializable {
private Boolean success;
private Integer errorCode;
private String errorMsg;
private T data;
public JsonResult() {
}
public JsonResult(boolean success) {
this.success = success;
this.errorCode = success ? ResultCode.SUCCESS.getCode() : ResultCode.COMMON_FAIL.getCode();
this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : ResultCode.COMMON_FAIL.getMessage();
}
public JsonResult(boolean success, ResultCode resultEnum) {
this.success = success;
this.errorCode = success ? ResultCode.SUCCESS.getCode() : (resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode());
this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : (resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage());
}
public JsonResult(boolean success, T data) {
this.success = success;
this.errorCode = success ? ResultCode.SUCCESS.getCode() : ResultCode.COMMON_FAIL.getCode();
this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : ResultCode.COMMON_FAIL.getMessage();
this.data = data;
}
public JsonResult(boolean success, ResultCode resultEnum, T data) {
this.success = success;
this.errorCode = success ? ResultCode.SUCCESS.getCode() : (resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode());
this.errorMsg = success ? ResultCode.SUCCESS.getMessage() : (resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage());
this.data = data;
}
}
3.ResultCode
package com.alanx.java.util;
/**
* @Description: Return code definition
* Regulations :
* #1 It means success
* #1001~1999 Interval indicates parameter error
* #2001~2999 Interval indicates user error
* #3001~3999 The interval indicates that the interface is abnormal
*/
public enum ResultCode {
/* success */
SUCCESS(200, " success "),
/* Default failure */
COMMON_FAIL(999, " Failure "),
/* Parameter error :1000~1999 */
PARAM_NOT_VALID(1001, " Invalid parameter "),
PARAM_IS_BLANK(1002, " The parameter is empty. "),
PARAM_TYPE_ERROR(1003, " Wrong parameter type "),
PARAM_NOT_COMPLETE(1004, " Missing parameter "),
/* User error */
USER_NOT_LOGIN(2001, " The user is not logged in "),
USER_ACCOUNT_EXPIRED(2002, " Account has expired "),
USER_CREDENTIALS_ERROR(2003, " Wrong password "),
USER_CREDENTIALS_EXPIRED(2004, " Password expired "),
USER_ACCOUNT_DISABLE(2005, " Account not available "),
USER_ACCOUNT_LOCKED(2006, " The account is locked "),
USER_ACCOUNT_NOT_EXIST(2007, " Account does not exist "),
USER_ACCOUNT_ALREADY_EXIST(2008, " Account already exists "),
USER_ACCOUNT_USE_BY_OTHERS(2009, " Account offline "),
/* Business error */
NO_PERMISSION(3001, " No authority ");
private Integer code;
private String message;
ResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/**
* according to code obtain message
*
* @param code
* @return
*/
public static String getMessageByCode(Integer code) {
for (ResultCode ele : values()) {
if (ele.getCode().equals(code)) {
return ele.getMessage();
}
}
return null;
}
}
4.ResultTool
package com.alanx.java.util;
/**
* @Description: Return body construction tool
*/
public class ResultTool {
public static JsonResult success() {
return new JsonResult(true);
}
public static <T> JsonResult<T> success(T data) {
return new JsonResult(true, data);
}
public static JsonResult fail() {
return new JsonResult(false);
}
public static JsonResult fail(ResultCode resultEnum) {
return new JsonResult(false, resultEnum);
}
}
3、 ... and 、Controller layer
After the first successful login , Store information in Rides in
package com.alanx.java.controller;
import com.alanx.java.bean.Users;
import com.alanx.java.service.UserService;
import com.alanx.java.util.JsonResult;
import com.alanx.java.util.JwtUtils;
import com.alanx.java.util.ResultTool;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/users")
public class UsersController {
@Resource
private UserService service;
@Resource
private StringRedisTemplate stringRedisTemplate;
@PostMapping("/login")
public String login(Users users) {
QueryWrapper<Users> wrapper = new QueryWrapper<>();
wrapper.eq("username", users.getUserName());
wrapper.eq("password", users.getPassWord());
List<Users> list = service.list(wrapper);
if (list.size() == 0) {
return JSON.toJSONString(ResultTool.fail()); // Failure returns an error code
}
Users u = list.get(0);
String token = JwtUtils.getJwtToken(u);
stringRedisTemplate.opsForValue().set(u.getId() + "", token, 1, TimeUnit.DAYS); // Store in redis in
JsonResult<String> result = ResultTool.success(token);
return JSON.toJSONString(result);
}
}
Use Postman Test the result. If the password is wrong, an error code will be returned

If the password is correct , There will be jwt

stay Redis Query results in , Copy results to JWT Official website After decoding, information other than the password will appear .


In the second part of the carrier, the decoded results can be customized , stay JwtUtils Class getJwtToken Method

边栏推荐
- 【TcaplusDB知识库】TcaplusDB单据受理-创建业务介绍
- Error building SqlSession问题
- Mysql database daily backup and scheduled cleanup script
- Niuke Xiaobai monthly race 52 E group logarithmic sum (inclusion exclusion theorem + dichotomy)
- Request header field XXXX is not allowed by access control allow headers in preflight response
- Top 30 open source software
- [tcapulusdb knowledge base] tcapulusdb doc acceptance - Introduction to creating game area
- 3H proficient in opencv (VIII) - shape detection
- Adobe Premiere foundation - cool text flash (14)
- 行程卡“摘星”热搜第一!刺激旅游产品搜索量齐上涨
猜你喜欢

Have you grasped the most frequently asked question in the interview about massive data processing?

Adobe Premiere foundation - sound adjustment (volume correction, noise reduction, telephone tone, pitch shifter, parameter equalizer) (XVIII)

ISO 32000-2 international standard 7.7

Adobe Premiere基础-常用的视频特效(裁剪,黑白,剪辑速度,镜像,镜头光晕)(十五)

The soft youth under the blessing of devcloud makes education "smart" in the cloud

Kubekey2.2.1 kubernetes1.23.7 offline package production +harbor Department summer and upload image

jdbc认识上手

Xiaomai technology x hologres: high availability of real-time data warehouse construction of ten billion level advertising

Servlet student management system (Mengxin hands-on version)

Codeworks 5 questions per day (1700 for each) - the next day
随机推荐
Serial port experiment based on stm32f103zet6 library function
lodash深拷贝使用
3H proficient in opencv (VIII) - shape detection
Kubekey2.2.1 kubernetes1.23.7 offline package production +harbor Department summer and upload image
3H proficient in opencv (VII) - color detection
JS merge two 2D arrays and remove the same items (collation)
How do I add SmartArt to slides in PowerPoint?
Lodash deep copy usage
金鱼哥RHCA回忆录:DO447构建高级作业工作流--使用事实缓存提高性能
NVIDIA installs the latest graphics card driver
[tcapulusdb knowledge base] tcapulusdb operation and maintenance doc introduction
【网络是怎么连接的】第三章 探索集线器,交换机和路由器
Record that the server has been invaded by viruses: the SSH password has been changed, the login fails, the malicious program runs full of CPU, the jar package fails to start automatically, and you ha
【TcaplusDB知识库】TcaplusDB单据受理-事务执行介绍
Yolov6+tensorrt+onnx: deployment based on win10+tensorrt8+yolov6+onnx
Test dble split function execution + import time-consuming shell script reference
Adobe Premiere foundation - cool text flash (14)
Top 30 open source software
[网鼎杯 2020 青龙组]AreUSerialz
Encryption and decryption of 535 tinyurl
