当前位置:网站首页>Using JWT to realize login function
Using JWT to realize login function
2022-07-07 09:20:00 【Wow, it's a small dish】
One 、 What is? jwt
1. What is? session
Want to know what is jwt, You need to know what it is first session, It can be understood in this way session, In a security situation , Some data needs to be saved on the server , According to the client's sessionId It can be recognized session, Then process the data .
session Generally, it is simple to store some , And more important information , For example, users id, User login status , Authority, etc .
Be careful , If the user Disabled cookie, that session You can't use , because session Use cookie The only one carried in id Can be found in the server
2. What is? jwt?
jwt All the way through json web token. 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.
3. Why use jwt Instead of using session
- session Is to store the client data in the memory of the server , When there is too much data on the customer service side , The memory overhead of the server is large ;
- session The data is stored on a server , Sharing cannot be achieved in distributed projects ;
- jwt Better security .
To make a long story short , If distributed , Cut only in session and jwt When choosing inside , You must choose jwt.
Two 、jwt principle
1. header head :
Include the type of token and the signature algorithm used
{
"alg":"HS625", // Signature algorithm
"type":"JWT" // Token type
}
Execute the request header base64 Encryption constitutes the first part
2.payload load
The load is where the data is loaded , Include statement ( Statements about user entities and other data ), Use Base64 Encoding ,
You can put payload The load is imagined as session The data of ,session Although stored in server memory , We should also prevent some accidents , For example, there are staff members who steal passwords , therefore ,session Sensitive information cannot be stored inside
{
"username": "zhangsan",
"dataAuth": "beijing"
}
3.signature Signature
take header and payload after base64 The encrypted data will be encrypted again after adding salt .
The salt value is only stored on the server , Can't let the cat out of the , If the disclosure is easy to cause the client to sign and issue by itself token, for example : Even without the login step , Know the user name username, Sign and issue by yourself token To access some data sensitive to data permissions .
3、 ... and 、 Use to login
1. Introduce dependencies
implementions('io.jsonwebtoken:jjwt:0.7.0')
2. Ready to configure
# token Private key , Stored in only sign and parse token The service side
jwt.secret=123456
# Expiration time , The unit is millisecond , Here is 24*60*60*1000,24 Within hours
jwt.expire=86400000
3. Create and parse JWT Tool class of
@ConfigurationProperties(prefix = "jwt")
@Component
@Data
public class JwtConfig {
private String secret;
private long expire;
/** * Issue jwt * * @param user * @return */
public String createJWT(User user) {
Date date = new Date();
Date expireDate = new Date(date.getTime() + expire);
Map<String, Object> claims = new HashMap<>();
claims.put("name", user.getUsername());
claims.put("id", user.getId());
String jwt = Jwts.builder()
// Set load content
.setClaims(claims)
// The issuance of time
.setIssuedAt(date)
// Expiration time
.setExpiration(expireDate)
// jwt The main body , For storage jwt All of us , You can save users id Or characters id
.setSubject(user.getName())
.compact();
return jwt;
}
/** * analysis JWT * * @param jwt * @return */
public Claims parseJWT(String jwt) {
Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJwt(jwt).getBody();
return claims;
}
}
4. Sign in token
@RequestMapping("login")
public Map<String, Object> login(@RequestParam(name = "name") String name, @RequestParam(name = "passWord") String passWord) {
User user = userService.findByUsernameAndPassword(name, passWord);
if (null == user ) {
throw new ControllerException("501", " Wrong user name or password ");
}
String token = jwtConfig.createJWT(user);
map.put("token", token);
return map;
}
5. Filter and its configuration class
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Resource
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
}
}
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Resource
private JwtConfig jwtConfig;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String url = request.getRequestURI();
// If you include login, Then directly verify the user name and password , There is no need to verify token, You can set the white list here
if (url.contains("/login")) {
return true;
}
String token = request.getHeader(jwtConfig.getHeader());
if (StringUtils.isEmpty(token)) {
token = request.getParameter(jwtConfig.getHeader());
}
if (null == token || token.isEmpty()) {
return false;
}
Claims claims = jwtConfig.parseJWT(token);
String userName = claims.get("name", String.class);
request.setAttribute("userName", subject);
return true;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
}
边栏推荐
- Panel display technology: LCD and OLED
- What is the use of PMP certificate?
- Pytest+request+allure+excel interface automatic construction from 0 to 1 [five nails / flying Book notice]
- 串口實驗——簡單數據收發
- STM32 serial port register library function configuration method
- Cesium load vector data
- The use of recycling ideas
- Leetcode daily questions (2316. count unreachable pairs of nodes in an undirected graph)
- Screen automatically generates database documents
- Postman setting environment variables
猜你喜欢
Jenkins modifies the system time
Mysql database transaction learning notes
Postman interface debugging method
Data association between two interfaces of postman
Yapi test plug-in -- cross request
Locust performance test 5 (analysis)
JVM 内存结构 详细学习笔记(一)
Run can start normally, and debug doesn't start or report an error, which seems to be stuck
Interview question: general layout and wiring principles of high-speed PCB
E-commerce campaign Guide
随机推荐
信息安全实验四:Ip包监视程序实现
JVM 内存结构 详细学习笔记(一)
Expérience de port série - simple réception et réception de données
Screen automatically generates database documents
正则匹配以XXX开头的,XXX结束的
(3/8)枚举的不当用法 之 方法参数(二)
Regularly modify the system time of the computer
[chaosblade: node disk filling, killing the specified process on the node, suspending the specified process on the node]
JWT certification used in DRF
答案在哪里?action config/Interceptor/class/servlet
What are the conditions for applying for NPDP?
Pycharm importing third-party libraries
Register address name mapping
[istio introduction, architecture, components]
端口复用和重映像
Jmeters use
Cesium does not support 4490 problem solution and cesium modified source code packaging scheme
PMP Exam details after the release of the new exam outline
Cesium load vector data
Pycharm create a new file and add author information