当前位置:网站首页>Basic introduction of JWT

Basic introduction of JWT

2022-07-07 06:50:00 Children haha

Preface

JWT It is mainly used for user login authentication , The traditional method is session authentication .

http It's a stateless agreement , When a user authenticates the user with the account name and password to the system , The next request needs another user authentication . Because we can't go through http The protocol knows which user sent the request , So if you want to know which user sent the request , Then you need to save a copy of user information on the server ( Save to session), Then return after successful authentication cookie Value passed to browser , Then the user can bring it with him at the next request cookie value , The server can identify which user sent the request , Is it certified , Whether the login expires .

session The shortcomings of certification are obvious , because session Is saved in the server , So if you deploy applications distributed , There will be session Problems that can't be shared , It's hard to expand .

JWT Introduction to

JWT:Json Web Token  It defines a compact 、 The self-contained way , Used as a JSON Objects transmit information securely between parties . This information can be verified and trusted , Because it's digitally signed .

  technological process :

  • Users use accounts 、 Password login application , The login request is sent to Authentication Server.
  • Authentication Server User authentication , Then create JWT String returned to client .
  • When a client requests an interface , On the request headband JWT.
  • Application Server verification JWT Legitimacy , If it is legal, continue to call the application interface and return the result

User information is saved on the client , The key is to generate JWT And analysis JWT.

JWT Data structure of

JWT Generally, it is such a string , It's divided into three parts , With "." separate .

xxxxx.yyyyy.zzzzz

Header: The first part is the head part , describe JWT Metadata Json object

{
    "alg": "HS256",
    "typ": "JWT"
}

 alg Property indicates the algorithm used for signature , The default is HMAC SHA256( Written as HS256),typ Property indicates the type of token ,JWT Token is uniformly written as JWT. Last , Use Base64 URL The algorithm will JSON Object to string save .

Payload: The second part is Payload, Also a Json object , In addition to containing the data to be transmitted , There are seven default fields to choose from .

Namely ,iss: The issuer 、exp: Due time 、sub: The theme 、aud: user 、nbf: Not available until 、iat: Release time 、jti:JWT ID Used to identify the JWT.

If custom fields , It can be defined as :

{
    // Default fields 
    "sub":" The theme 123",
    // Custom field 
    "name":"java Technology enthusiasts ",
    "isAdmin":"true",
    "loginTime":"2021-12-05 12:00:03"
}

JSON Objects also use Base64 URL Algorithm converted to string save .

Signature: The third part is signature . This is how it was generated , First, you need to specify a secret, The secret Save only in the server , Make sure that other users don't know . And then use Header The specified algorithm pair Header and Payload Calculate , Then you get a signature hash .

JWT The advantages of :

  • json The generality of the format , therefore JWT Can support cross language , such as Java、JavaScript、PHP、Node wait .
  • You can use Payload Store some non sensitive information .
  • Easy to transmit ,JWT Simple structure , Small byte footprint .
  • There is no need to save session information on the server , Easy to apply extensions .

Use JWT 

Import dependence

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>

Create a tool class , Used to create jwt String and parsing jwt


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;

import java.util.Date;

/**
 *
 * @description JWT: token token Generate 
 */
public class TokenUtil {

    // token The period of validity 
    private static final long EXPIRATION = 86400L;//1day = 86400L

    /**
     *
     * @description  establish token Tool method 
     */
    public static String createToken(User user) {
        JwtBuilder builder = Jwts.builder();
        builder.setAudience(user.getUserCode()) //  This user.getUserCode() It is the parameter I need later 
                .setIssuer("xxx")
                .claim("userId", user.getId()) // userId  It is the parameter I need later , This is set according to your own needs 
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000));
        String accessToken = builder.compact();
        return accessToken;
    }

    /**
     * 
     * @description  verification token Back to the user code
     */
    public static String validateToken(String token) {
        Claims claims = Jwts.parserBuilder().build().parseClaimsJwt(token).getBody();
        String userCode = claims.getAudience();
        return userCode;
    }

    /**
     * 
     * @description  verification token Back to the user ID
     */
    public static String getUserIdFromToken(String token) {
        Claims claims = Jwts.parserBuilder().build().parseClaimsJwt(token).getBody();
        String userId = claims.get("userId", String.class);
        return userId;
    }
}

Some minor modifications , I didn't use the third part here .
link :https://www.zhihu.com/question/485758060/answer/2257869896

原网站

版权声明
本文为[Children haha]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070234219924.html