当前位置:网站首页>JWT(Json Web Token)
JWT(Json Web Token)
2022-06-24 22:42:00 【Passerby Chen】
1.JWT(Json Web Token)
JWT Token by Header( Head )、Payload( load )、Signature( Signature ) Three parts , The essence is a string . Use points in the middle of each part (.) Separate , such as :xxxxx.yyyyy.zzzzz
Header( Head )
The header includes the type of token ( namely JWT) And the hash algorithm used ( Such as HMAC、SHA256 or RSA), The main statement is JWT The signature algorithm of .
Payload( load )
The second part is the load , The content is also a Json object , It's a place to store valid information , It can store JWT Off the shelf fields provided , Than Such as :iss( Issuer ),exp( Expiration time stamp ), sub( For users ) etc. , You can also customize fields . It is not recommended to store sensitive information in this section , Because this part can decode and restore the original content . It mainly carries various declarations and transmits plaintext data .
Signature( Signature )
The third part is signature , This part is used to prevent JWT The content has been tampered with . This part uses base64url Code the first two parts , Use points after coding (.) Join to form a string , Finally using header In a statement Signature algorithm to sign .
JWT The main purpose of is to transfer declarations in a secure way between the server and the client .
The main application scenarios are as follows :
- authentication Authentication;
- to grant authorization Authorization;
- associated recognition ;
- Client session ( Stateless session );
- Client secrets .
2.JWS、JWE、JWK、JWKset、JWA and nonsecure JWT difference
JWS | JSON Web Signature( Signature ) | Have Signature( Signature ) Part of the JWT go by the name of JWS, That is to say JWT The signature of the JWS, That is to say JWT Signature |
JWE | JSON Web Encryption( encryption ) | JWT part payload Encrypted JWT |
JWK | JSON Web Key | JWT The key of ( Private key ), That's what we often say scret |
JWKset | JSON Web Key set | JWT key set In asymmetric encryption , What is needed is a key pair, not a separate key , It will be explained later |
JWA | JSON Web Algorithms( Algorithm ) | At present JWT The cryptographic algorithm used |
nonsecure JWT | When the signature algorithm of the header is set to none When , The JWT It's not safe ; Because part of the signature is vacant , Everyone can modify | No, Signature( Signature ) Part of the JWT go by the name of nonsecure JWT, That is, unsafe JWT |
JJWT | Used in JVM Create and validate on JSON Web token (JWTs) The library of | Is based on JWT、JWS、JWE、JWK and JWA RFC canonical Java Realization ( Is to provide end-to-end JWT Create and verify Java library ) |
JWS The third part of the is a visa information , This visa information consists of three parts :
base64UrlEncode(header):JWT The first part of the token .
base64UrlEncode(payload):JWT The second part of the token .
secret: The key used for signing .
3.JWT How user authentication works
1. The client uses the user name and password to request login
2. The server receives the request , Verify user name and password
3. After successful verification , The server will issue a token, Put this again. token Return to the client
4. Client received token Then you can store it , For example, put it in cookie in
5. Each time the client requests resources from the server, it needs to carry the certificate issued by the server token, Can be in cookie perhaps header Middle carry
6. The server receives the request , Then go to verify the client request token, If the validation is successful , Just return the request data to the client

4. Realization JWT Generate token
4.1 stay Maven In Engineering pom.xml Add JWT Related dependencies
<!--JWT token -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>4.2JWT Tool class
import com. Company name .SystemConstants;
import io.jsonwebtoken.*;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
public class AppJwtUtil {
// TOKEN Is valid for one day (S)
private static final int TOKEN_TIME_OUT = 3600;
// encryption KEY
private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
// Minimum refresh interval (S)
private static final int REFRESH_TIME = 300;
// production ID
public static String createToken(Long id) {
Map<String, Object> claimMaps = new HashMap<>();
claimMaps.put("id", id);
long currentTime = System.currentTimeMillis();
return Jwts.builder()
.setId(UUID.randomUUID().toString())
.setIssuedAt(new Date(currentTime)) // The issuance of time
.setSubject("system") // explain
.setIssuer("heima") // Signer information
.setAudience("app") // Receiving user
.compressWith(CompressionCodecs.GZIP) // Data compression
.signWith(SignatureAlgorithm.HS512, generalKey()) // encryption
// One hour overdue
.setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000)) // Expiration time stamp
.addClaims(claimMaps) //cla Information
.compact();
}
/**
* obtain token Medium claims Information
* @param token
* @return
*/
private static Jws<Claims> getJws(String token) {
return Jwts.parser()
.setSigningKey(generalKey())
.parseClaimsJws(token);
}
/**
* obtain payload body Information
* @param token
* @return
*/
public static Claims getClaimsBody(String token) {
try {
return getJws(token).getBody();
} catch (ExpiredJwtException e) {
return null;
}
}
/**
* obtain hearder body Information
* @param token
* @return
*/
public static JwsHeader getHeaderBody(String token) {
return getJws(token).getHeader();
}
/**
* Is it overdue
* @param token
* @return 1 It works 0 Invalid 2 Has expired
*/
public static Integer verifyToken(String token) {
try {
Claims claims = AppJwtUtil.getClaimsBody(token);
if (claims == null) {
return SystemConstants.JWT_FAIL;
}
return SystemConstants.JWT_OK;
} catch (ExpiredJwtException ex) {
return SystemConstants.JWT_EXPIRE;
} catch (Exception e) {
return SystemConstants.JWT_FAIL;
}
}
/**
* Encryption by string generation key
* @return
*/
public static SecretKey generalKey() {
byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
}4.3JWT System constant class
public class SystemConstants {
//JWT TOKEN Has expired
public static final Integer JWT_EXPIRE = 2;
//JWT TOKEN It works
public static final Integer JWT_OK = 1;
//JWT TOKEN Invalid
public static final Integer JWT_FAIL = 0;
}边栏推荐
- Learn more about the practical application of sentinel
- Online filing process
- 2022-06-16 工作记录--JS-判断字符串型数字有几位 + 判断数值型数字有几位 + 限制文本长度(最多展示n个字,超出...)
- String exercise summary 2
- NIO多路复用之Selector的使用
- [QT] QT event handling
- 磁盤的結構
- Certificate photo processing
- Unable to use the bean introduced into the jar package
- 如何提取网页中的日期?
猜你喜欢

Row and column differences in matrix construction of DX HLSL and GL glsl

Description of transparent transmission function before master and slave of kt6368a Bluetooth chip, 2.4G frequency hopping automatic connection

ACL (access control list) basic chapter - Super interesting learning network

结合源码剖析Oauth2分布式认证与授权的实现流程

Genesis公链与美国一众加密投资者齐聚Consensus 2022

Information update on automatic control principle

VRRP skills topic

Envoy obtain the real IP address of the client

socket done

Raspberry pie preliminary use
随机推荐
Panorama of enterprise power in China SSD industry
How to extract dates from web pages?
Row and column differences in matrix construction of DX HLSL and GL glsl
04A中断的配置
详细了解Redis的八种数据类型及应用场景分析
Disk structure
2022-06-16 工作记录--JS-判断字符串型数字有几位 + 判断数值型数字有几位 + 限制文本长度(最多展示n个字,超出...)
Can AI chat robots replace manual customer service?
Principle of IP routing
Relationnet++: a representation of fusion of multiple detection targets based on transformer | neurips 2020
img2pdf
Ansible basic configuration
What aspects should we start with in the feasibility analysis of dry goods?
A pit in try with resources
Zero code can apply data visualization to enterprise management
结构体的内存对齐
Web security XSS foundation 06
磁盘的结构
Docker 安装 Redis-5.0.12,详细步骤
[Software Engineering] key points at the end of the period