JWT - 如何使用JWT

时间 2019/3/29 9:15:51 加载中...


How do JSON Web Tokens work?
In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned. Since tokens are credentials, greate care must be taken to prevent security issues.In general, you should not keep tokens longer than required.


Whenever the user wants to access a protected route or resource. the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following:

用户收到服务器端返回的JWT后,以后每次请求资源,都在请求头中带上JWT,一般放在请求头的 Authorization 中,使用 Bearer 架构。就像下面这样:

Authorization: Bearer <token>

This can be, in certain cases, a stateless authorization mechanism. The server’s protected routes will check for a valid JWT in the Authorization header, and if it’s present, the user will be allowed to access protected resources.If the JWT contains the necessary data,the need to query the database for certain operations may be reduced, though this may not always be the case.



If the token is sent in the Authorization header, Cross-Origin Resource Sharing(CORS) won’t be an issue as it doesn’t use cookies.


The following diagram shows how a JWT is obtained and used to access APIs or resources:


1.The application or client requests authorization to the authorization server. This is performed through one of the different authorization flows. For examples, a typical OpenID connect compliant web application will go through the oauth/authorize endpoit using the authorization code flow.

2.When the authorization is granted, the authorization server returns an access token to the application.

3.The application uses the access token to access a protected resource(like an API).

  1. 首先,客户端向授权服务器发起请求,请求授权。
    比如,一个典型的OpenID Connect的页面程序将请求oauth/authorize这样的接口。
    OpenID Connect
    authorization code flow

  2. 当授权允许后,授权服务器会返回一个 access token 给客户端。

  3. 客户端使用 access token 来访问受保护的资源(比如API)。

Do note that with signed tokens, all the information contained within the token is exposed to users or other parties, even though they are unable to change it. This means you should not put secret information within the token.