JWT (JSON WEB Token) uses the scene correctly

Source: Internet
Author: User
Tags hmac

https://www.jianshu.com/p/af8360b83a9f, don't use JWT anymore!ThoughtWorks China2017.08.16 08:51* words 2882 read 71543 reviews 172 Summary:
    • In Web apps, it's not a good idea to use JWT instead of a session
    • Usage Scenarios for JWT

Sorry, when back to the heading party. I do not deny the value of JWT, but it is often misused.

What is JWT

According to Wikipedia definition, theJSON WEB Token(JWT, read as a [/d?? T/]), is a JSON-based token that is used to declare a claim on the network. A JWT is usually made up of three parts: header information (header), message body (payload), and signature (signature).

The header information specifies the signature algorithm used by the JWT:

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

HS256Indicates that a hmac-sha256 is used to generate the signature.

The message body contains the intent of the JWT:

‘{"loggedInAs":"admin","iat":1422779638}‘//iat表示令牌生成的时间

Unsigned tokens are stitched together by the base64url encoded header information and the body of the message (using "."). Delimited), the signature is computed by a private key:

‘secretkey‘  unsignedToken = encodeBase64(header) + ‘.‘ + encodeBase64(payload)  signature = HMAC-SHA256(key, unsignedToken) 

Finally, the signature is encoded on unsigned token tail stitching base64url (also using "."). Separated) is the JWT:

‘.‘ + encodeBase64(payload) + ‘.‘ + encodeBase64(signature) # token看起来像这样: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI 

JWT is often used as a resource to protect the server (resource), and the client usually sends the JWT via HTTP headers to the server Authorization , which uses its own saved key to calculate and verify the signature to determine if the JWT is trustworthy:

Authorization: Bearer eyJhbGci*...<snip>...*yu5CSpyHI
How could that be misused?

With the popularity of restful APIs in recent years, the use of HTTP headers to pass authentication tokens seems to be a legitimate one, while a single page application (SPA), front-end separation architecture seems to be enabling more and more Web applications to abandon the historic cookie-session authentication mechanism, Instead, use JWT to manage the user session. Those who support the programme believe that:

1. The programme is easier to scale horizontally

In the cookie-session scenario, the cookie contains only one session identifier, and the user information, authorization list, etc. are stored in the session on the server. If the authentication information in the session is stored in a JWT, there is no need for the session to exist on the server. When the service side expands horizontally, it is not necessary to deal with session replication/session sticky (sticky session) or the introduction of external session storage.

From this point of view, this advantage does exist, but in fact the external session storage scheme is very mature (such as Redis), with the help of some frameworks (such as spring-session and Hazelcast), Session duplication is also not an imaginary problem. So unless your app visits are very, very, very large (omit n very big here), using Cookie-session with the external session store is fully sufficient.

2. This scheme can protect against CSRF attacks

Cross-site request forgery Cross-site requests forgery (referred to as CSRF, read as [Sea-surf]) is a typical attack that exploits cookie-session vulnerabilities, Here we borrow an example from spring-security to explain CSRF:

Assuming you frequently use bank.example.com for online transfers, Bank.example.com's front-end code submits an HTTP request when you submit a transfer request:

POST /transfer HTTP/1.1Host: bank.example.comcookie: JsessionID=randomid; Domain=bank.example.com; Secure; HttpOnlyContent-Type: application/x-www-form-urlencodedamount=100.00&routingNumber=1234&account=9876

It's convenient for you not to log out of bank.example.com, and then visit a malicious website that contains a form with an HTML page:

<Formaction="Https://bank.example.com/transfer"Method="POST" ><InputType="Hidden"Name="Amount"Value="100.00"/><input type=  "hidden" name= "Routingnumber" value= "Evilsroutingnumber"/> <input type= "hidden"  Name= "account" value= " Evilsaccountnumber "/> <input type=< Span class= "hljs-string" > "submit" value= "click to send!" /></FORM>        

You are attracted by the "click-to-Send" button, and you have transferred $100 to the attacker's account when you order the submit buttons. Real-world attacks can be more covert, and malicious Web pages may use JavaScript to automate submissions. Although there is no way for a malicious website to steal your session cookie (thus impersonating you), your cookie will be automatically sent to bank.example.com when a malicious website requests it.

As a result, some people think that the front-end code can effectively protect CSRF by sending a JWT over the HTTP header to the server instead of automatically via a cookie. In this scenario, the service-side code returns a JWT in the header of the HTTP response after the authentication is completed, the front-end code stores the JWT in the local storage, or the server stores the Httponly=false JWT directly in the cookie.

When initiating a request to the server, use JavaScript to remove the JWT (otherwise the front-end JavaScript code does not have permission to fetch data from the cookie) and then send it back to the server through the header for authentication. Because the code of a malicious website could not get the JWT in Bank.example.com's cookie/local storage, this approach does protect csrf, but saving the JWT in cookie/local storage might give another attack , we'll discuss it in more detail: cross-site Scripting attack--XSS.

3. The programme is more secure

Because JWT requires a secret key, there is an algorithm that generates a token that appears unreadable, and many people mistakenly believe that the token is encrypted. But in fact, the secret key and algorithm is used to generate the signature, the token itself is unreadable only because of the base64url encoding, can be decoded directly, so if the JWT stored sensitive information, relative cookie-session data on the server side, more insecure.

In addition to these misconceptions, using JWT to manage the session has the following drawbacks:

    1. more space to occupy. If all kinds of information in the original server session are stored on the client in the JWT, it may cause the space of JWT to become larger, consider the space limitation of the cookie, and if put in local Storage, it may be attacked by XSS.

    2. less secure. This is specifically a scenario where the JWT is stored in the local storage and then taken out as an HTTP header and sent to the server using JavaScript. Storing sensitive information in the local storage is not secure, is susceptible to cross-site scripting attacks, and cross-site scripting, referred to as XSS, is an "HTML injection", which is called "Cross-domain scripting" because most of the attacks are cross-domain scripts. These script codes can steal data from cookies or local storage. You can see how the XSS attacks are explained in this article.

    3. cannot invalidate a issued token. All the authentication information is in JWT, because there is no status on the service side, even if you know that a JWT has been stolen, you have no way to invalidate it. There's nothing you can do until the JWT expires (you should definitely set the expiration time).

    4. data expiration is not an easy deal. similar to the previous one, JWT is a bit like a cache, because the issued tokens cannot be invalidated, and you can only tolerate "expired" data until it expires.

When you see this, you may find that it's not a good idea to keep a JWT in the local storage and use JWT to manage the session, is it possible to use JWT "correctly" to manage the session? Like what:

    • No longer use local storage to store JWT, use cookies, and set httponly=true, which means that JWT can only be saved by the server and automatically returned via cookies to protect against XSS attacks
    • A random value is added to the JWT's content as the CSRF token, and the CSRF token is stored in the cookie by the server, but the httponly=false is set so that the front-end JavaScript code can take the CSRF token and act as an HTTP when the API is requested The header passes back. Service side in the authentication, remove the CSRF token from the JWT and get the CSRF token comparison in the header to achieve protection against CSRF attacks
    • Taking into account the space limitations of the cookie (about 4k or so), the only "enough" authentication information is placed in the JWT as much as possible, and other information is placed in the database and then acquired when needed, as well as addressing the previously mentioned data expiration issues

This plan seems to be very good, congratulations, you re-invented the cookie-session, possible to achieve is not necessarily the existing good.

So what is a JWT supposed to do?

My colleague has done an image of the explanation:

The most suitable scenario for JWT (and in fact, SAML) is "invoicing", or "signing".

In the paper-working era, multi-departmental, multi-organizational collaboration often need to hold a department leader's "signature" or "seal" to the B Department "use" or "access" the corresponding resources, in fact, this "leader Signature/seal" is JWT, is a certain authority by the entity "issued" and "authorized" Notes. " Generally, this instrument is verifiable (the leader signature/seal can be verified and difficult to imitate), non-tamper (the modified document is not accepted, unless it is re-signed at the Alteration place); and this kind of note is generally "disposable" use, after access to the corresponding resources, The bill is generally showings by the resource holder for subsequent audits and retrospective purposes.

Give two examples:

  1. Staff Li Lei need to take a day off, so fill out the request for leave, Li Lei in the Department of Management after obtaining the signature, the leave to the HR department Han Meimei, Han Meimei confirmed that the leader signed, will take the leave list, and make corresponding records in the company attendance sheet.
  2. Employees Li Lei and Han Meimei because of work to use the company car one day, so fill in the car application form, after signing Li Lei will apply to the team driver Lao Wang, ride the old Wang driving vehicle out of office, while Lao Wang will use the car application form to recover and archive.

In the above two examples, "Leave application Form" and "Car application Form" is the payload in JWT, the leadership signature is base64 after the digital signature, leadership is issuer, "HR Department Han Meimei" and "driver Lao Wang" is the audience of JWT, Audience needs to verify that the leader signature is legitimate, and that it is valid to grant the appropriate permissions based on the resources requested in the payload, while the JWT is retracted.

In a system-integrated scenario, JWT is more suitable for one-time operation of certification:

Service B Hello, service A tells me that I can operate <JWT content, this is my voucher (that is, JWT)

Here, service A is responsible for authenticating the user's identity (equivalent to the leader's approval of a leave of absence in the previous example) and issuing a very short expiration time to the browser (equivalent to the absence form in the previous example), and the browser (equivalent to the leave employee in the previous example) brings the JWT to service B's request. Service B (equivalent to the HR employee in the previous example) can verify the JWT to determine whether the user is authorized to perform the operation. In this way, service B becomes a secure, stateless service.

Summarize
    1. In Web applications, don't use JWT as a session, and in most cases, the traditional cookie-session mechanism works better.
    2. JWT is suitable for one-time command authentication, and a very short-term JWT is issued, even if the risk of exposure is small, because each operation will generate a new JWT, so there is no need to save the JWT, truly stateless.

JWT (JSON WEB Token) uses the scene correctly

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.