Teach you step by step to implement JWT authentication and authorization



foreword

This blogger will use CSDN to record the experience and knowledge he has personally gained and learned on the way to study software development. Interested friends can pay attention to the blogger!
Perhaps a person can go fast alone, but a group of people can go farther!

1. Introduction

In our previous article, we introduced the authentication mechanism of token (token) authentication, but in this article, we will introduce JWT authentication (JSON Web Token authentication) for you.

2. The relationship between Token authentication and JWT authentication

Do you feel the pressure now? Not only have you learned Cookie authentication, Session authentication, but also a Token authentication, and now there is a JWT authentication. Don’t worry, this JWT authentication is not a novel authentication method. It is a Token-based authentication mechanism. Token authentication is a general authentication method. We can use different types of Tokens for authentication, and JWT is one of the Token types.

Here we have to make a distinction. The Token authentication mechanism introduced in the previous article is a broad concept and a general term, which covers the methods of using different types of Tokens for authentication. In addition to JWT, there are other types of tokens, such as time-based tokens (Time-based Tokens) and access tokens (Access Tokens). These tokens can use different formats and authentication mechanisms, but they are all credentials used to authenticate users and authorize access to protected resources.

So after clarifying the relationship, let's enter the text!

3. What is JWT authentication?

JWT authentication (JSON Web Token authentication) is a Token-based authentication mechanism. It uses JSON Web Token (JWT) as an authentication credential, and by verifying the JWT to confirm the user's identity and authorize the user to access protected resources.

4. Composition of JWT

As mentioned above, JWT is just one of many token types, so its composition is the focus of our study.

JWT is an open standard (RFC 7519) that defines a compact and self-contained way to represent and transmit information. It consists of three parts:

  1. Header : Contains metadata and algorithm information describing the JWT, such as the signature algorithm used.
  2. Payload : Contains the data declared by JWT, which can contain user identity information, authorization information and other custom data.
  3. Signature : Sign the header and payload using a key and a specified signature algorithm for data integrity and verification.

insert image description here

1. Header

The header usually contains two parts: the token type (typ) and the signature algorithm (alg). This information is used to describe the type of JWT and the encryption algorithm used. For example, a typical header could be in the following JSON format:

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

In the above example, "alg" indicates that the signature algorithm is HMAC SHA-256 (HS256), and "typ" indicates that the token type is JWT.

2. Payload

The payload is the body of the JWT and contains the data to be transmitted. The payload can contain some predefined claims (Claims), and can also contain custom claims. The predefined declarations fall into three categories:

  • Registered Claims: These claims are a set of predefined standard claims, including iss (issuer), sub (subject), aud (audience), exp (expiration time), nbf (effective time) and iat (issue time), etc.
  • Public Claims: These claims are self-defined claims for users to define freely, but it is recommended to follow certain naming conventions to avoid conflicts.
    Private Claims: These claims are also custom claims, but in order to avoid conflicts, it is recommended to name them in the form of a namespace, such as "company_name".
    The following is the JSON format of an example payload:
{
  "sub": "user123",
  "name": "John Doe",
  "iat": 1629012345
}

In the above example, "sub" means the user with the subject "user123", "name" means the user name is "John Doe", and "iat" means the JWT was issued at 1629012345 (UNIX timestamp).

3. Signature

The signature is the third part of the JWT and is used to verify the integrity and authenticity of the JWT. Signatures are typically generated using data in the header and payload and a secret key. The process of generating a signature is to encode the header and payload, and then use the specified signature algorithm (such as HMAC, RSA, etc.) to encrypt. The resulting signature string will be appended to the end of the JWT.

Example of a signature:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secretKey
)

In the above example, "header" indicates the Base64 encoded string of the header, "payload" indicates the Base64 encoded string of the payload, and "secretKey" indicates the secret key used to generate the signature.

A complete JWT is formed by concatenating these three parts with a period (.):

base64UrlEncode(header) + "." +
base64UrlEncode(payload) + "." +
signature

The final JWT can be transmitted between client and server as authentication credentials, and the authenticity and integrity of the JWT can be verified by verifying the signature.

Of course, many people will doubt the security of this token. JWT is composed of three parts, separated by dots header, payload and signature

  1. The header part declares what algorithm needs to be used to generate the signature

  2. The payload part is some specific data, such as validity period and the like

  3. Then the content of the header and payload will be encoded by BASE64. Note that it is encoding, not encryption, that is, it can be easily decoded. Although the JWT is not stored on the server, the server needs to save a password. This password must be combined with two encodings. Carry out algorithmic operations, and finally get the signature information. The algorithm used here is the algorithm just declared by the header. The signed information, that is, the signature part, so that a complete and largest JWT can be sent to the client. If we modify the three parts, one of the characters, the entire maximum JWT will be wrong, and the three parts are associated, so JWT has a certain degree of security.

quote but teacher
The token is the user information encrypted by the server, the server sends the token to the browser, and the browser uses cookie or storage to save the cookie. Then the browser brings the token every time it sends a request, and the server decrypts it and confirms the user's login.

Five, JWT authentication workflow

The workflow of JWT authentication generally involves the following steps:

  1. User authentication:
    When a user authenticates, they typically provide credentials (such as a username and password) that identify them. The server needs to verify the validity of these credentials, usually by comparing them with user credentials stored in a database.

  2. Generation of JWT:
    If the user is authenticated, the server will generate a JWT as the authentication credential. The process of generating a JWT consists of the following steps:

    • Create a JSON object containing the header and payload.
    • Base64-encode the header and payload to generate the first part of the JWT.
    • Use the key on the server and the specified signature algorithm to sign the encoded header and payload to generate a signature.
    • Concatenate the signature with the encoded header and payload to generate a full JWT.
  3. Sending and storing of JWT:
    The server sends the generated JWT to the client, usually by returning the JWT as part of the response (for example, in the header of the HTTP response or as part of the response). Clients will typically store the JWT locally, such as in the browser's local storage or in memory.

  4. Authentication for subsequent requests:
    In subsequent requests, the client sends the JWT as authentication credentials to the server. This is usually done by placing the JWT in a request header (such as an Authorization header) or sending it to the server as part of a request parameter (such as a query string or form data).

  5. Verification and parsing of JWT:
    After receiving the request, the server needs to verify the validity and integrity of the JWT and parse the information in it. The process of validation and parsing includes the following steps:

    • Get the JWT from the request.
    • Check that the JWT's signature is valid to ensure the JWT has not been tampered with.
    • Decode the header and payload of the JWT to obtain the information in it.
  6. User authorization and access to protected resources:
    The server confirms the user's identity by verifying the validity of the JWT and obtaining the user's identity information in it. Based on the user's identity information, the server can make an authorization judgment to determine whether the user has the right to access the requested resource. If the user is authorized to access the resource, the server will return the corresponding data or perform the corresponding operation.

The entire JWT authentication workflow is based on stateless, the server does not need to store session state in the backend, each request is independent. JWT acts as an authentication credential, providing a simple, secure and scalable way to authenticate users and authorize them to access protected resources.

insert image description here

6. Code example

Here is a sample code using the Java JWT library (jjwt):

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JWTExample {
     
     
    private static final String SECRET_KEY = "yourSecretKey";
    private static final long EXPIRATION_TIME = 86400000; // 24小时

    public static void main(String[] args) {
     
     
        // 创建JWT
        String token = createJWT("user123");

        // 验证和解析JWT
        if (validateJWT(token)) {
     
     
            String username = parseJWT(token);
            System.out.println("解析到的用户名:" + username);
        } else {
     
     
            System.out.println("JWT验证失败");
        }
    }

    public static String createJWT(String username) {
     
     
        Date now = new Date();
        Date expiration = new Date(now.getTime() + EXPIRATION_TIME);

        String token = Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();

        return token;
    }

    public static boolean validateJWT(String token) {
     
     
        try {
     
     
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
     
     
            return false;
        }
    }

    public static String parseJWT(String token) {
     
     
        Jws<Claims> claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
        return claims.getBody().getSubject();
    }
}

In the above example, createJWTthe method is used to create a JWT, in which the user name, issuance time, and expiration time are set, and the HS256 algorithm is used for signing. validateJWTThe method is used to verify the legitimacy of the JWT, and judge by parsing and verifying the signature of the JWT. parseJWTThe method is used to parse the JWT and extract the username information in it.

Please note that the key in the above code SECRET_KEYis used to sign and verify the JWT, please make sure to replace it with the actual key and keep it safe. In addition, the expiration time set in the example is 24 hours (86400000 milliseconds), we can adjust it according to our own needs.

Using this sample code, you can create a JWT containing username information, and verify and parse the JWT to get the username inside.

7. Summary

Don't make the three too complicated

  1. The session is born and saved on the server side, and the server dominates everything.
  2. Cookie is a kind of data carrier, put the session in the cookie and send it to the client side, and the cookie is sent out with each request of HTTP.
  3. The token is born on the server, but it is saved on the browser side. The client dominates everything. It can be placed in a cookie or storage. Holding the token is like holding a token, allowing access to the server.
  4. Server verification is a prerequisite. The cookie is saved on the client, but not encrypted by the server; the session is saved on the client, but encrypted and saved by the server; the token is saved on the client, but encrypted and not saved by the server.
  5. Session is a server-side mechanism for storing and managing user identity and status information, while Cookie is a mechanism for storing session ID and other data on the client side. Token is a lightweight authentication and authorization mechanism that can be transmitted as stateless credentials. Both Cookie and Token can be used to transfer identity information and status information between the client and the server to realize the functions of authentication and status management.

Guess you like

Origin blog.csdn.net/weixin_52533007/article/details/132110578