当前位置:网站首页>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;
}
}
边栏推荐
- Run can start normally, and debug doesn't start or report an error, which seems to be stuck
- 端口复用和重映像
- Postman setting environment variables
- JVM garbage collection detailed learning notes (II)
- What are the suggestions for PMP candidates?
- Connecting mobile phone with ADB
- Why is access to the external network prohibited for internal services of the company?
- 嵌套(多级)childrn路由,query参数,命名路由,replace属性,路由的props配置,路由的params参数
- RuntimeError: Calculated padded input size per channel: (1 x 1). Kernel size: (5 x 5). Kernel size c
- How long does the PMP usually need to prepare for the exam in advance?
猜你喜欢

C language pointer (exercises)

Upgrade Alibaba cloud RDS (relational database service) instance to com mysql. jdbc. exceptions. Troubleshooting of jdbc4.communicationsexception

Mysql database index study notes
![Pytest+request+allure+excel interface automatic construction from 0 to 1 [familiar with framework structure]](/img/33/9fde4bce4866b988dd2393a665a48c.jpg)
Pytest+request+allure+excel interface automatic construction from 0 to 1 [familiar with framework structure]

NVIC interrupt priority management

Systick滴答定时器

2020 year end summary

STM32 serial port register library function configuration method

Unittest simple project

信息安全实验四:Ip包监视程序实现
随机推荐
[SVN] what is SVN? How do you use it?
Full link voltage test of the e-commerce campaign Guide
C language pointer (Part 2)
Reflections on the way of enterprise IT architecture transformation (Alibaba's China Taiwan strategic thought and architecture practice)
C语言指针(下篇)
External interrupt to realize key experiment
Some pit avoidance guidelines for using Huawei ECS
MySql数据库-事务-学习笔记
Locust performance test 4 (custom load Policy)
Mysql database transaction learning notes
LeetCode每日一题(2316. Count Unreachable Pairs of Nodes in an Undirected Graph)
Self awakening from a 30-year-old female programmer
Simulation volume leetcode [general] 1609 Parity tree
Storage of data in memory
Record of structured interview
Pycharm create a new file and add author information
2021 year end summary
SAP MM STO单据的外向交货单创建后新加ITEM?
Implementation of corner badge of Youmeng message push
STM32串口寄存器库函数配置方法