当前位置:网站首页>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;
}
}
边栏推荐
- Entity of cesium data visualization (Part 1)
- [istio introduction, architecture, components]
- DRF authentication, permissions, and flow restrictions (only for views in DRF)
- Record of structured interview
- Selenium mouse sliding operation event
- 超十万字_超详细SSM整合实践_手动实现权限管理
- Jenkins automated email
- [SVN] what is SVN? How do you use it?
- Unityshader introduction essentials personal summary -- Basic chapter (I)
- Where is the answer? action config/Interceptor/class/servlet
猜你喜欢
Serial port experiment - simple data sending and receiving
Reading notes of pyramid principle
JWT certification used in DRF
Pytest+request+allure+excel interface automatic construction from 0 to 1 [familiar with framework structure]
Huawei hcip datacom core_ 03day
Postman interface test (II. Set global variables \ sets)
E-commerce campaign Guide
浏览器中如何让视频倍速播放
How to pass the PMP Exam in a short time?
MySql数据库-索引-学习笔记
随机推荐
Interface test API case, data and interface separation
What is the rating of Huishang futures company? Is it safe to open an account? I want to open an account, OK?
JVM 内存结构 详细学习笔记(一)
Count the number of words C language
Chaosblade: introduction to chaos Engineering (I)
Summary of PMP learning materials
C语言指针(习题篇)
Serializer & modelserializer of DRF serialization and deserialization
Test Engineer Interview Questions 2022
Do you have any certificates with high gold content?
十二、排序
Interview question: general layout and wiring principles of high-speed PCB
How to use Arthas to view class variable values
H3C vxlan configuration
E-commerce campaign Guide
Leetcode刷题记录(数组)组合总和、组合总和 II
When inputting an expression in the input box, an error is reported: incorrect string value:'\xf0\x9f... ' for column 'XXX' at row 1
(3/8)枚举的不当用法 之 方法参数(二)
Storage of data in memory
Idea development environment installation