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

What is the method of JWT authentication login

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

In this article, the editor introduces in detail "what is the method of JWT authentication login", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "what is the method of JWT authentication login" can help you solve your doubts, following the editor's ideas slowly in depth, let's learn new knowledge together.

Traditional authentication starts with a login scenario.

You've used so many websites and APP, and many of them need to log in, so let's pick a scenario and talk about it.

In an e-commerce system, for example, if you want to place an order, you first need to register an account. After you have an account, you need to enter a user name (such as a mobile phone number or mailbox) and a password to complete the login process. After that, if you re-enter the system within a period of time, you do not need to enter your user name and password. You need to enter your user name and password again only if you have not logged in for a long time (for example, if you have not logged in for a month).

For those frequently used websites or applications, you usually don't need to enter a password for a long time, so that you can't remember the passwords of some frequently used websites or APP after you change a computer or a mobile phone.

The early Cookie-Session authentication method

In the early days, the Internet was dominated by web, and the client was the browser, so Cookie-Session was the most commonly used authentication method in the early days. Up to now, some web websites still use this way to do authentication.

The authentication process is roughly as follows:

The user enters the user name and password or logs in to the system by SMS verification code

After server verification, create a Session message, save the SessionID to cookie, and send it back to the browser

The next time the client initiates a request, it automatically brings the cookie information, and the server obtains the Session information through cookie for verification.

But why it is a traditional way of authentication, because now everyone has a smartphone, many people do not use computers, usually use a variety of APP on mobile phones, such as Taobao, pinduoduo and so on. Under this trend, the traditional Cookie-Session has encountered some problems: 1. First of all, Cookie-Session can only be used in web scenarios. If it is APP, APP has no place to store cookie. Today's products basically provide both web and APP, and some products even have APP.

2. To say the least, your product only supports web, and cross-domain issues should also be considered, but Cookie cannot cross-domain. Take Tmall Mall, for example, when you enter Tmall Mall, you will see the menus of Tmall supermarket, Tmall International and Tmall members at the top. Clicking on these menus will lead to different domain names, and the cookie under different domain names is different. You can't get the cookie of domain B under domain A, even if it's a subdomain.

3. If it is a distributed service, the problem of Session synchronization should be considered. Today's Internet sites and APP are basically distributed deployment, that is, there is more than one machine on the server. When a user logs in on the page, the login action must be requested to one of the servers. Your identity information has to be preserved. The traditional way is to save Session.

Next, here comes the problem. When you visit several pages, a request is routed to another server (not the one you logged in) through load balancing. When the background receives a request, it checks the user's identity information and permissions, so the interface begins to obtain user information from the Session. However, this server is not the one that logged in at that time, and your Session is not stored, so the backend service thinks that you are a non-logged-in user and cannot return data to you.

Therefore, in order to avoid this situation, we should do Session synchronization. After one server receives the login request, after the current server saves the Session, it also synchronizes with several other servers.

4. Cookie has the risk of CSRF (cross-site request forgery). Cross-site request forgery is an attack method that hijacks users to perform unintended operations on currently logged-in Web applications. CSRF takes advantage of the site's trust in users' web browsers. To put it simply, it is the attacker who uses some technical means to deceive the user's browser to visit a website he has authenticated and to run some operations (such as buying goods). Because the browser has been authenticated, the website visited will be considered to be initiated by a real user. For example, I am a hacker, and I found that there is a CSRF vulnerability in a technical website that you often visit. Publishing articles supports html format, so I add some dangerous content to html, such as

Suppose src points to the payment address of a shopping site you usually use (of course, for example, the real attack is not that simple), if you have logged in before and the cookie that identifies your identity has been saved. When you browse to my post, as soon as the img tag is loaded, the CSRF attack will work and pay to the site without your knowledge.

Cookie-Session modified version

As there are many problems in the traditional Cookie-Session authentication, the above scheme can be modified. 1. Modify Cookie. Since Cookie cannot be used in non-browsers such as APP, it is not necessary to use cookie for client storage. What should I change it to? Client-side databases can be used in local storage,APP in web, which enables cross-domain implementation and avoids CSRF.

2. Session is no longer stored on the server side, and the Session information is stored in Redis and other in-memory databases, which not only improves the speed, but also avoids the problem of Session synchronization.

After the transformation, it has been transformed into the following authentication process:

The user enters the user name and password or logs in to the system by SMS verification code

After verification, the server stores the data structure constructed by the authentication information into Redis, and returns the key value to the client.

The client gets the returned key and stores it in local storage or local database

Next time the client requests again, append the key value to the header or the request body

According to the obtained key, the server goes to Redis to obtain authentication information

The following two figures demonstrate the process of first-time login and non-first-time login, respectively.

After a fierce transformation, the problems existing in the traditional Cookie-Session mode are solved. This transformation needs to be done by the developers themselves in the project. It must be time-consuming and laborious to transform, and there may be loopholes.

JWT comes out

At this time, JWT can play. JWT is a specific implementation of a modified version of Cookie-Session, which saves you the time of building your own wheels. Another advantage of JWT is that you do not have to store authentication information (such as token) on the server, which is provided entirely by the client. The server can verify the user's legitimacy according to the decryption algorithm provided by JWT itself, and this process is secure.

If you are new to JWT, the most questionable point may be: why JWT can rely entirely on the client (such as browser) to achieve authentication function, authentication information is all stored in the client, how to ensure security?

JWT data structure

The final form of JWT is a string, which consists of a header, a payload, and a signature, separated by a "." Like this:

Head

The header is represented in JSON format and is used to indicate the token type and encryption algorithm. The form is as follows, indicating the use of JWT format, encryption algorithm using HS256, which is the most commonly used algorithm, in addition to many other.

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

Corresponding to the red header part of the above image, Base64 coding is required.

Load

Used to store data needed by the server, such as user information, such as name, gender, age, etc., it is important to note that important confidential information should not be put here, such as passwords.

{"name": "ancient kites", "introduce": "handsome"}

In addition, JWT also specifies seven fields for developers to choose from.

Iss (issuer): issuer

Exp (expiration time): expiration time

Sub (subject): topic

Aud (audience): audience

Nbf (Not Before): effective time

Iat (Issued At): time of issue

Jti (JWT ID): number

This part of the information is also encoded in Base64.

Signature

There is a formula for calculating the signature.

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

Calculated by using the HMACSHA256 algorithm, this method has two parameters, the first parameter is (base64-encoded header + base64-encoded payload) connected by a dot, and the latter parameter is a custom string key, which should not be exposed to the client, but should be known by the server.

Mode of use

After understanding the structure and algorithm of JWT, how to use it? Suppose I have a website here.

1. When a user logs in to the website, he or she needs to enter a user name, password or SMS to verify the login. When the login request arrives at the server, the server verifies the account and password, then calculates the JWT string and returns it to the client.

2. After the client gets the JWT string, it is stored in cookie or the LocalStorage of the browser.

3. Send the request again, for example, when requesting the user to set up the page, add the JWT string to the HTTP request header, or put it directly in the request body.

4. After the server gets the JWT string, it uses the header of base64 and the payload part of base64 to calculate the signature part by HMACSHA256 algorithm. Compare whether the calculated result is consistent with the received signature part. If the result is consistent, there is no problem with this request. If it is inconsistent, the request is expired or illegal.

How do you ensure security?

The key to ensure security is HMACSHA256 or the same type of encryption algorithm, because the encryption process is irreversible, so it can not be transmitted to the key information according to the JWT transmitted to the front end.

In addition, different headers and payloads get different signatures after encryption, so if someone changes the information of the payload, the final encrypted result must be different from that before the change, so, the final verification result is an illegal request.

Is it safe for someone else to get the full JWT?

Suppose that the fields related to the permission level are stored in the payload part, and the robber wants to change it to a higher permission level after getting the JWT string. As mentioned above, it will definitely not succeed in this case, because the encrypted signature will be different, and the server may easily distinguish it.

Well, if the robber does not change it and use it directly, then there is no way to prevent it from being stolen by robbers to a greater extent, we should use the HTTPS protocol instead of the HTTP protocol, which can effectively prevent some intermediate hijacking attacks.

Some students are about to say, it's not safe at all. If you get the JWT string, you can easily simulate the request. That's true, but the premise is how can you get it? is there anything you can do besides the intermediate hijacking mentioned above?

Unless the robber directly took your computer, in that case, sorry, not only JWT is not secure, any other website, any way of authentication is not secure.

Although such cases are rare, you should still pay attention to setting the expiration time reasonably when using JWT, not too long.

A question.

The problem with JWT is that many development teams give up using it, which is that once a JWT token is issued, the server cannot discard it until it expires. There are many applications that allow only one newly logged-in client to use by default. Without multiple logins, JWT cannot do so because new tokens are issued, but the old tokens are still available before expiration. In this case, the server needs to add the corresponding logic.

Commonly used JWT libraries

The official website of JWT lists the corresponding libraries for various languages, including the following for Java.

Take java-jwt as an example.

1. Introduce the corresponding Maven package.

Com.auth0 java-jwt 3.10.3

2. When logging in, call the create method to get a token and return it to the front end.

Public static String create () {try {Algorithm algorithm = Algorithm.HMAC256 ("secret"); String token = JWT.create () .withIssuer ("auth0") .withSubject ("subject") .withClaim ("name", "ancient kite") .withClaim ("introduce", "handsome") .sign (algorithm); System.out.println (token); return token } catch (JWTCreationException exception) {/ / Invalid Signing configuration / Couldn't convert Claims. Throw exception;}}

3. After a successful login, the token is placed in the header or the request body when the request is initiated again, and the server verifies the token.

Public static Boolean verify (String token) {try {Algorithm algorithm = Algorithm.HMAC256 ("secret"); JWTVerifier verifier = JWT.require (algorithm) .withIssuer ("auth0") .build (); / / Reusable verifier instance DecodedJWT jwt = verifier.verify (token); String payload = jwt.getPayload (); String name = jwt.getClaim ("name"). AsString (); String introduce = jwt.getClaim ("introduce"). AsString (); System.out.println (payload) System.out.println (name); System.out.println (introduce); return true;} catch (JWTVerificationException exception) {/ / Invalid signature/claims return false;}}

4. Generate token with create method and verify it with verify method.

Public static void main (String [] args) {String token = create (); Boolean result = verify (token); System.out.println (result);}

Get the following results

EyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzdWJqZWN0IiwiaW50cm9kdWNlIjoi6Iux5L-K5r2H5rSSIiwiaXNzIjoiYXV0aDAiLCJuYW1lIjoi5Y-k5pe255qE6aOO562dIn0.ooQ1K_XyljjHf34Nv5iJvg1MQgVe6jlphxv4eeFt8pAeyJzdWIiOiJzdWJqZWN0IiwiaW50cm9kdWNlIjoi6Iux5L-K5r2H5rSSIiwiaXNzIjoiYXV0aDAiLCJuYW1lIjoi5Y-k5pe255qE6aOO562dIn0 ancient kites were handsome and unrestrained true

JWT strings created using the create method can be verified.

If I modify the load part of the JWT string in the middle of the two dots, and then call the verify method to verify, a JWTVerificationException exception will occur and will not pass the verification.

Read here, this article "what is the method of JWT authentication login" article has been introduced, want to master the knowledge of this article also need everyone to practice and use to understand, if you want to know more related articles, welcome to follow the industry information channel.

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