JWT use another voice

Speak true, do not use the JWT!

 

The present session to be saved in a data field reserved to remove sensitive client 

 
  • In Web applications, the use of alternative JWT session is not a good idea
  • JWT for usage scenarios

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

What is the JWT

According to Wikipedia, JSON WEB Token (JWT, pronounced [/ dʒɒt /]), is based on JSON for some statements claimed token (token) on the network. JWT usually consists of three parts: the header information (header), message body (payload) and signature (signature).

Header specifies the signature algorithm used by the JWT:

header = '{"alg":"HS256","typ":"JWT"}' 

HS256 He expressed using HMAC-SHA256 to generate a signature.

Message body contains a JWT's intentions:

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

Unsigned token by the base64urlsplice variants encoded information and messages from (using the separator "."), Is calculated from the signature by the private key:

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

Finally, the token stitching on the tail of an unsigned base64urlsignature encoded (also using separate. "") Is the JWT:

token = encodeBase64(header) + '.' + encodeBase64(payload) + '.' + encodeBase64(signature) 

# token看起来像这样: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI 

JWT is often used as a resource (resource) to protect the server, the client usually JWT via HTTP Authorizationis sent to the server header, the server uses its own stored key calculation, verify the signature to determine the credibility of the JWT:

Authorization: Bearer eyJhbGci*...<snip>...*yu5CSpyHI

Then how do you misuse it

In recent years began to rage RESTful API using HTTP header authentication token to pass seemed to grow as it should, while the single-page application (SPA), before and after the end of the separation architecture seems to contribute to a growing number of WEB application to abandon the historic cookie- session authentication mechanism in favor of JWT to manage user session. The program supports people think:

1. This embodiment is easier to scale-

In the cookie-session, the inner cookie contains only a session identifier, such as user information, and so on authorization list stored in the session on the server side. If the authentication information in the session are saved in JWT, the server would not need to exist in the session. When the end of the horizontal extension of the service time, do not copy processing session (session replication) / session adhesions (Sticky session) or the session storage redistribute.

 

From this perspective, this advantage does exist, but in fact the external storage session program has been very mature (such as Redis), with the help of some of the Framework's (such as spring-session and Hazelcast ), session replication also did not imagine trouble. So unless your application views very very very (N omitted here very) large, using cookie-session session with the external memory is completely sufficient.

2. The program protects against CSRF attacks

CSRF Cross-Site Request Forgery (abbreviated CSRF, pronounced [sea-surf]) is a typical cookie-session using vulnerability to attack, Borrowing spring-security an example to explain CSRF:

Suppose you often use bank.example.com online transfers, when you submit the transfer request bank.example.com the front-end code will submit an HTTP request:

POST /transfer HTTP/1.1
Host: bank.example.com cookie: JsessionID=randomid; Domain=bank.example.com; Secure; HttpOnly Content-Type: application/x-www-form-urlencoded amount=100.00&routingNumber=1234&account=9876 

You do not log out of convenience bank.example.com, followed by a visit a malicious Web site, the site's HTML page contains a form like this:

<form action="https://bank.example.com/transfer" method="post"> <input type="hidden" name="amount" value="100.00"/> <input type="hidden" name="routingNumber" value="evilsRoutingNumber"/> <input type="hidden" name="account" value="evilsAccountNumber"/> <input type="submit" value="点击就送!"/> </form> 

You were attracted to "click send" when you point the submit button you have $ 100 to turn the attacker's account. The reality of the attacks may be more subtle, page malicious sites may automatically be submitted using Javascript. Although there is no way to steal your session cookie (so fake your identity) malicious sites, but malicious Web site sends a request to bank.example.com, your cookie will automatically be sent in the past.

Therefore, some people think JWT front-end code will be sent to the server via HTTP header (instead of cookie automatically sent via) can be effective protection CSRF. In this embodiment, the server code After completion of the authentication, returns the HTTP response header in the JWT, the front-end code is stored in the Local Storage JWT stand in, or directly to the server HttpOnly = false stored in a cookie JWT.

 

When initiating a request to the server, taken with JWT Javascript (or distal Javascript code does not obtain data from the cookie), and then sent back through the header by the authentication server. Since malicious code can not get bank.example.com site's cookie / Local Storage of JWT, that really protects against CSRF, but will save JWT in cookie / Local Storage may give another opportunity to attack , we will discuss it in detail: cross-site scripting attacks --XSS.

3. The scheme is more secure

Since JWT requires a secret key, there is an algorithm to generate a token unreadable looks, a lot of people mistaken for the token is encrypted. But in fact the secret key and algorithm are used to generate the signature, because the token itself is only readable base64urlcoding may be decoded directly, so if JWT if stored sensitive information, the relative data in the cookie-session to the server He said less secure.

In addition to these misconceptions, session management, as well as the use of the following disadvantages JWT:

  1. More space occupied. If the original server-side session kinds of information are placed in the presence of JWT stored in the client, may cause JWT space occupied by large, cookie to consider space constraints and other factors, if placed in the Local Storage, it is likely to be XSS attack.

  2. 更不安全。这里是特指将JWT保存在Local Storage中,然后使用Javascript取出后作为HTTP header发送给服务端的方案。在Local Storage中保存敏感信息并不安全,容易受到跨站脚本攻击,跨站脚本(Cross site script,简称xss)是一种“HTML注入”,由于攻击的脚本多数时候是跨域的,所以称之为“跨域脚本”,这些脚本代码可以盗取cookie或是Local Storage中的数据。可以从这篇文章查看XSS攻击的原理解释。

  3. 无法作废已颁布的令牌。所有的认证信息都在JWT中,由于在服务端没有状态,即使你知道了某个JWT被盗取了,你也没有办法将其作废。在JWT过期之前(你绝对应该设置过期时间),你无能为力。

  4. 不易应对数据过期。与上一条类似,JWT有点类似缓存,由于无法作废已颁布的令牌,在其过期前,你只能忍受“过期”的数据。

看到这里后,你可能发现,将JWT保存在Local Storage中,并使用JWT来管理session并不是一个好主意,那有没有可能“正确”地使用JWT来管理session呢?比如:

  • 不再使用Local Storage存储JWT,使用cookie,并且设置HttpOnly=true,这意味着只能由服务端保存以及通过自动回传的cookie取得JWT,以便防御XSS攻击
  • 在JWT的内容中加入一个随机值作为CSRF令牌,由服务端将该CSRF令牌也保存在cookie中,但设置HttpOnly=false,这样前端Javascript代码就可以取得该CSRF令牌,并在请求API时作为HTTP header传回。服务端在认证时,从JWT中取出CSRF令牌与header中获得CSRF令牌比较,从而实现对CSRF攻击的防护
  • 考虑到cookie的空间限制(大约4k左右),在JWT中尽可能只放“够用”的认证信息,其他信息放在数据库,需要时再获取,同时也解决之前提到的数据过期问题

这个方案看上去是挺不错的,恭喜你,你重新发明了cookie-session,可能实现还不一定有现有的好。

那究竟JWT可以用来做什么

我的同事做过一个形象的解释:

JWT(其实还有SAML)最适合的应用场景就是“开票”,或者“签字”。

在有纸化办公时代,多部门、多组织之间的协同工作往往会需要拿着A部门领导的“签字”或者“盖章”去B部门“使用”或者“访问”对应的资源,其实这种“领导签字/盖章”就是JWT,都是一种由具有一定权力的实体“签发”并“授权”的“票据”。一般的,这种票据具有可验证性(领导签名/盖章可以被验证,且难于模仿),不可篡改性(涂改过的文件不被接受,除非在涂改处再次签字确认);并且这种票据一般都是“一次性”使用的,在访问到对应的资源后,该票据一般会被资源持有方收回留底,用于后续的审计、追溯等用途。

举两个例子:

  1. 员工李雷需要请假一天,于是填写请假申请单,李雷在获得其主管部门领导签字后,将请假单交给HR部门韩梅梅,韩梅梅确认领导签字无误后,将请假单收回,并在公司考勤表中做相应记录。
  2. 员工李雷和韩梅梅因工外出需要使用公司汽车一天,于是填写用车申请单,签字后李雷将申请单交给车队司机老王,乘坐老王驾驶的车辆外出办事,同时老王将用车申请单收回并存档。

在以上的两个例子中,“请假申请单”和“用车申请单”就是JWT中的payload,领导签字就是base64后的数字签名,领导是issuer,“HR部门的韩梅梅”和“司机老王”即为JWT的audience,audience需要验证领导签名是否合法,验证合法后根据payload中请求的资源给予相应的权限,同时将JWT收回。

放到系统集成的场景中,JWT更适合一次性操作的认证:

服务B你好, 服务A告诉我,我可以操作<JWT内容>, 这是我的凭证(即JWT)

Here, A service responsible for authenticating user identity (equivalent to the above example, the leadership of the granting of leave), and promulgated a JWT very short expiration time to the browser (equivalent to leave alone in the example above), browser (the equivalent of cases the employees leave) of the band B JWT in the request to the service, the service B (corresponding to the embodiment of the employees HR) may be determined whether the user is authorized to perform the operation by verifying JWT. In this way, the service B has become a safe stateless served.

to sum up

  1. In Web applications, do not use the session as JWT, in most cases, the traditional cookie-session mechanisms work better
  2. JWT command for a one-time certification, issued a very short period of JWT, even when exposed to the risk is very small, since each JWT will generate a new operation, and therefore did not need to save JWT, truly stateless.

Text / ThoughtWorks Zhou Yugang

Author: ThoughtWorks
link: https: //www.jianshu.com/p/af8360b83a9f
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/871735097-/p/12079471.html