JWT user authentication for frontend and backend separation and jwt user authentication for Separation

Source: Internet
Author: User

JWT user authentication for frontend and backend separation and jwt user authentication for Separation

Why does user authentication be required for separate development at the front-end? The reason is that the HTTP protocol is not stored (stateless), which means that when we verify a user through the account and password, it will forget the information in the next request. So our program does not know who it is, so we have to verify it again. To ensure system security, we need to verify whether the user is logged on.

Traditional Mode

How to verify the user's logon information and permissions when the frontend and backend are separated through Restful APIs for data interaction. In the original project, the most traditional and simplest method is used. The backend generatesToken, and saveToken and the corresponding user ID to the database or Session, and thenThe token is sent to the user and saved to the browser cookie. Then, the browser requests the cookie and the backend queries the user based on the cookie value to verify whether the cookie has expired.

However, there are many problems in this way. If an XSS vulnerability occurs on our page, the cookie can be read by JavaScript, And the XSS vulnerability may cause User token leakage, which serves as the backend user identification, cookie Leakage means that user information is no longer secure. Although we can avoid XSS injection by escaping the output content and using CDN, no one can guarantee that this problem will not occur in large projects.

You can also set httpOnly and secure items when setting cookies. After httpOnly is set, the cookie cannot be read by JS. the browser automatically adds it to the request header. If secure is set, the cookie can only be transmitted over HTTPS. The secure option can filter out some XSS injection using the HTTP protocol, but it cannot be completely blocked.

The httpOnly option makes JS unable to read cookies, so there is no need to worry about XSS injection. However, setting httpOnly poses another problem, that is, Cross-Site Request Forgery is easily caused by XSRF. When your browser opens this page, another page can easily request the content of this page across sites. Because the cookie is sent by default.

In addition, if you save the verification information in the database, the backend needsTokenId, which increases the database query and storage overhead. If the verification information is stored in the session, the storage pressure on the server is increased. Can we leave the server alone for query? If we generateToken follows certain rules. For example, we use symmetric encryption algorithms to encrypt users.Id FormationToken, the server only needs to decryptToken to know the user'sId. However, I just want to give an example. If this is the case, as long as your symmetric encryption algorithm is leaked, other people can use this encryption method for forgery.Token, so all user information is no longer secure. Well, we can use asymmetric encryption algorithms to do this. In fact, there is a standard that we will introduce next to JWT.

Json Web Token(JWT)

JWT is an open standard (RFC 7519). It defines a simple and self-contained Method for securely transmitting information between communication parties in the form of JSON objects. JWT can use the HMAC algorithm or the RSA public key pair for signature. It has two features:

Compact)

It can be sent through URL, POST parameter, or HTTP header. Because the data volume is small, the transmission speed is fast.

Self-contained)

The load contains the information required by all users, avoiding multiple queries to the database.

JWT Composition

Header

The header contains two parts: the token type and the encryption algorithm used.

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

It uses Base64 encoding to form the first part of the JWT structure. If you use Node. js, you can use the base64url package of Node. js to obtain this string.

Base64 is an encoding, that is, it can be translated back to its original form. It is not an encryption process.

Payload

This part is where we store the information. You can put the user ID and other information here. The JWT specification gives a detailed introduction to this part, commonly used by iss (issuer), exp (expiration time), sub (target user), aud (receiver), iat (issue time ).

{ "iss": "lion1ou JWT", "iat": 1441593502, "exp": 1441594722, "aud": "www.example.com", "sub": "lion1ou@163.com"}

Similarly, it uses Base64 encoding to form the second part of the JWT structure.

Signature

The first two parts are encoded using Base64, that is, the front-end can unlock the information in it. Signature needs to use the encoded header and payload as well as a key provided by us, and then use the Signature algorithm (HS256) specified in the header for Signature. The purpose of the signature is to ensure that JWT has not been tampered.

The three parts pass through. The connection is our JWT. It may look like this, and the length seems to be related to your encryption algorithm and private key.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU3ZmVmMTY0ZTU0YWY2NGZmYzUzZGJkNSIsInhzcmYiOiI0ZWE1YzUwOGE2NTY2ZTc2MjQwNTQzZjhmZWIwNmZkNDU3Nzc3YmUzOTU0OWM0MDE2NDM2YWZkYTY1ZDIzMzBlIiwiaWF0IjoxNDc2NDI3OTMzfQ.PA3QjeyZSUh7H0GfE0vJaKW4LjKJuC3dVLQiY4hii8s

In fact, some people may think about this step, and the HTTP request will always carry a token, so that the token will be transferred to occupy unnecessary bandwidth. If you think so, you can decompress HTTP2 and HTTP2 to compress the header. I believe this problem is also solved.

Purpose of Signature

The signature process in the last step is to sign the header and the load content to prevent the content from being tampered. If someone decodes the header and the content of the load and then encodes it, And then adds the previous signature combination to form a new JWT, the server determines that the new header and load signature are different from the signature attached to JWT. If you need to sign the new header and load and do not know the key used for server encryption, the signature is different.

Information exposure

Here you will surely ask a question: Base64 is a type of encoding that is reversible, so will my information be exposed?

Yes. Therefore, in JWT, no sensitive data should be added to the load. In the preceding example, the User ID is transmitted. This value is actually not sensitive and is generally known as secure. However, content like passwords cannot be placed in JWT. If you put your password in JWT, a malicious third party can quickly learn your password through Base64 decoding.

Therefore, JWT is suitable for transmitting some non-sensitive information to Web applications. JWT is also often used to design user authentication and authorization systems, and even implement Single-point login for Web applications.

Use JWT First, the front-end sends its user name and password to the backend interface through the Web form. This process is generally an http post request. We recommend that you use SSL-encrypted transmission (https protocol) to prevent sensitive information from being sniffed. After the backend checks the user name and password, it uses other information such as the user id as the JWT Payload (load), concatenates it with the header in Base64 encoding, and then signs it to form a JWT. The JWT is a string in the same shape as lll. zzz. xxx. The backend returns the JWT string to the front end as the result of successful logon. The front-end can save the returned results on localStorage or sessionStorage. When you log out, the front-end can delete the stored JWT. The frontend puts JWT into the Authorization bit in the HTTP Header during each request. (Solving XSS and XSRF problems) check whether the backend exists. If yes, verify the validity of JWT. For example, check whether the signature is correct, check whether the Token expires, and check whether the Token receiver is itself (optional ). After the verification is passed, the backend uses the user information contained in JWT for other logical operations and returns the corresponding results. Differences between the storage id and the Session storage id

The biggest drawback of Session-based user ID storage is that the Session is stored on the server, which requires a large amount of server memory and may save many States for large applications. In general, large applications also need to use some KV databases and a series of cache mechanisms to store sessions.

The JWT method disperses the user status to the client, which can significantly reduce the memory pressure on the server. In addition to user IDs, you can also store other user-related information, such as whether the user is an administrator or a group of users. Although the JWT method puts some computing pressure on the server (such as encryption, encoding, and decoding), the pressure may be nothing compared to the disk storage. Whether or not to use data to speak in different scenarios.

Single Sign-on

The Session method is used to store user IDs. At the beginning, user sessions are only stored on one server. For sites with multiple subdomain names, each subdomain name must correspond to at least one different server, for example:Www.taobao.com,Nv.taobao.com,Nz.taobao.com,Login.taobao.com. So if you want to implementAfter logging on to login.taobao.com, you can still get the Session under another subdomain name, which requires us to synchronize the Session on multiple servers. The JWT method does not solve this problem because the user's status has been transferred to the client.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.