JWT - 如何使用JWT

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

JWT的使用

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.

在认证中,当用户使用凭证(账号密码)登录成功后,服务器端会返回一个JWT,因为JWT是凭证,因此必须非常小心,防止出现安全问题,一般情况下,token的保留时间不要超过自己所需的时间。

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.

在某些情况下,这可以认为是无状态的授权机制,服务器的安全路由会检查请求头中是否有Authorization,且是否有一个有效的JWT。

另外,如果JWT中包含有自己所需要的信息的话,那么向数据库拿这些信息的过程就可以省略掉了。虽然情况并非总是如此。

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.

如果token是通过Authorization发送给服务器的话,那么“跨域资源共享”也将不会再是一个问题,因为我们没有使用cookie。

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

下面的图展示了如何获取JWT和并使用来访问资源。

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.

再次强调,已签名的token中所包含的信息对用户和其它人来说,仍然是可见的。虽然别人不能修改它(token中的内容)。这也就意味着你不应该把私密信息放在token中。(比如说用户密码)

扫码分享
版权说明
作者:SQBER
文章来源:http://www.sqber.com/articles/json-web-token-use.html
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。