Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to apply JWT

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to apply JWT". In daily operation, I believe many people have doubts about how to apply JWT. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to apply JWT". Next, please follow the editor to study!

Overview of JWT

   JSON WEB TOKEN is an open standard based on JSON (RFC 7519) for passing declarations between network application environments. The token is designed to be compact and secure and is particularly suitable for single sign-on (SSO) scenarios at distributed sites.

The declaration of    JWT is generally used to transfer authenticated user identity information between the identity provider and the service provider in order to obtain resources from the resource server, and can also add some additional declaration information necessary for other business logic. The token can also be directly used for authentication or can be encrypted.

   A JWT is actually a string, which consists of three parts, a header, a payload, and a signature.

Application scenario

Authorization (Authorization): this is the most common scenario for using JWT. Once the user logs in, each subsequent request will contain a JWT, allowing the user to access the routes, services, and resources allowed by the token. Single sign-on is a feature of JWT that is widely used today because it has little overhead and can be easily used across domains.

Information Exchange (Information Exchange): JSON Web Tokens is undoubtedly a good way to securely transmit information between parties. Because JWT can be signed, for example, with a public / private key pair, you can be sure that the sender is who they say it is. In addition, because the signature is calculated using headers and payloads, you can also verify that the content has not been tampered with.

Authentication Mechanism based on token

   token-based authentication mechanism is similar to http protocol is also stateless, it does not need to retain the user's authentication information or session information on the server. This means that applications based on token authentication mechanism do not need to consider which server the user has logged in, which facilitates the expansion of the application.

The process goes like this:

The user uses the username and password to request the server

The server verifies the information of the user

The server sends a token to the user through authentication

The client stores the token and attaches this token value to each request

The server validates the token value and returns data

This token must be passed to the server on each request, and it should be stored in the request header. In addition, the server should support the CORS (cross-source resource sharing) policy, which is generally fine with Access-Control-Allow-Origin: * on the server.

JWT is composed of three pieces of information, which are used in the text. The links together make up the Jwt string. It's like this:

The composition of eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQJWT

The first part of the    we call it the header, the second part we call it the payload, which is similar to the things carried on the plane, and the third part is the signature.

Header (head)

It consists of two parts:

Type of token ("JWT")

Algorithm name (for example: HMAC SHA256 or RSA, etc.)

The complete head looks like the following JSON:

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

The header is then encrypted with base64 (the encryption can be decrypted symmetrically), forming the first part.

EyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9

Playload (load)

Load is the place where valid information is stored. There are three types of declarations:

Registered claims: declaration registered in the standard

Public claims: a public statement

Private claims: private declaration

Declaration of registration in the standard (recommended but not mandatory):

Iss: issuer of jwt

Sub: the user for which jwt is targeted

Aud: the party that receives the jwt

Exp: the expiration time of jwt, which must be greater than the issuing time

Nbf: defines when the jwt is not available.

Iat: the issuing time of the jwt

Jti: the unique identity of the jwt, mainly used as an one-time token to avoid replay attacks.

Public statement:

Public statements can add any information, generally adding user-related information or other necessary information needed by the business. However, it is not recommended to add sensitive information because this part can be decrypted on the client side.

Private declaration:

Private declaration is a declaration jointly defined by providers and consumers, and it is generally not recommended to store sensitive information, because base64 is symmetrically decrypted, which means that this part of the information can be classified as plaintext.

Define payload:

{"sub": "123456", "name": "John", "admin": true}

Then encrypt it with base64 to get the second part of the Jwt.

EyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9

Signature (Visa)

The third part of jwt is a visa information, which consists of three parts:

Header (after base64)

Payload (after base64)

Secret

This part requires the use of base64 encrypted header and base64 encrypted payload. Concatenate the string, and then add salt secret combination encryption through the encryption method declared in header, and then constitute the jwt

The third part.

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

Use these three parts. Concatenate into a complete string to form the final jwt:

EyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Note: secret is stored on the server side, and the signing and generation of jwt is also on the server side. Secret is used for jwt signing and jwt verification, so it is your server's private key and should not be revealed in any scenario. Once the client knows about the secret, it means that the client can sign the jwt itself.

How to apply

Generally, Authorization is added to the request header and marked with Bearer:

Headers: {'Authorization':' Bearer'+ token}

The server validates the token and returns the appropriate resource if the verification passes.

Identity Authentication of Token & identity Authentication of Server

Server-based authentication

Let's take a look at how we did it before.

The HTTP protocol is stateless, that is, if we have authenticated a user, the next time he requests, the server does not know who I am, and we must authenticate again.

Traditionally, authenticated user information is stored on a server, such as Session. The next time the user requests, he / she takes Session ID, and the server checks to see if the user has been authenticated.

There are some problems with server-based authentication:

Sessions: after each user authentication is passed, the server needs to create a record to store the user information, usually in memory. As more and more users pass the authentication, the server will spend more and more money here.

Scalability: because Session is in memory, this brings some scalability problems.

CORS: when we want to expand our application so that our data can be used by multiple mobile devices, we must consider the problem of cross-resource sharing. We may encounter the problem of forbidding requests when we use AJAX calls to get resources from another domain name.

CSRF: users are vulnerable to CSRF attacks.

The difference between JWT and Session

Similarly, they all store user information; however, Session is on the server side and JWT is on the client side.

The biggest problem of storing user information in Session mode is that it takes up a lot of server memory and increases the overhead of the server.

The JWT method distributes the user state to the client, which can obviously reduce the memory pressure on the server.

The state of Session is stored on the server side, the client only has session id;, and the state of Token is stored on the client side.

How does Token-based authentication work

Token-based authentication is stateless and no user information is stored in the server or Session.

The absence of session information means that the application can extend and add more machines as needed without worrying about where the user is logged in.

Although this implementation may be different, the main process is as follows:

User requests access with username and password

The server validates user credentials

The application provides a token to the client

The client stores the token and carries it with each subsequent request

The server verifies token and returns data

Note:

Token is required for every request

The Token should be placed in the request header

We also need to set up the server to accept requests from all domains, using Access-Control-Allow-Origin: *

Benefits of using Token

Stateless and extensible: Tokens is stored on the client. Completely stateless and scalable. Our load balancer can pass users to any server because there is no state or session information anywhere.

Security: Token is not Cookie. (The token, not a cookie.) Token is sent every time a request is made. Moreover, since no Cookie is sent, it also helps to prevent CSRF attacks. Even if you store the token in the client's Cookie in your implementation, this Cookie is just a storage mechanism, not an authentication mechanism. There is no session-based information to operate because we don't have a session!

Also, the token expires after a period of time, when the user needs to log in again. It helps us stay safe. There is also a concept called token revocation, which allows us to invalidate a particular token or even a set of token based on the same license.

The difference between JWT and OAuth

OAuth3 is an authorization framework, and JWT is an authentication protocol.

No matter which way you use, remember to use HTTPS to ensure the security of your data.

OAuth3 is used when logging in with a third-party account (such as using weibo, qq, and github to log in to an app), while JWT is used when the front and back ends are separated and the background API needs to be simply protected.

At this point, the study on "how to use JWT" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report