2016年(48)
分类: Web开发
2016-10-14 17:46:25
Koa JWT authentication middleware.
Koa middleware that validates JSON Web Tokens and sets ctx.state.user (by default) if a valid token is provided.
This module lets you authenticate HTTP requests using JSON Web Tokens in your (node.js) applications.
See this article for a good introduction.
点击(此处)折叠或打开
The JWT authentication middleware authenticates callers using a JWT token. If the token is valid, ctx.state.user (by default) will be set with the JSON object decoded to be used by later middleware for authorization and access control.
The token is normally provided in a HTTP header (Authorization), but it can also be provided in a cookie by setting the opts.cookie option to the name of the cookie that contains the token. Custom token retrieval can also be done through the opts.getToken option. The provided function is called in the normal Koa context and should return the retrieved token.
Normally you provide a single shared secret in opts.secret, but another alternative is to have an earlier middleware set ctx.state.secret, typically per request. If this property exists, it will be used instead of the one in opts.secret.
点击(此处)折叠或打开
Alternatively you can conditionally run the jwt middleware under certain conditions:
点击(此处)折叠或打开
For more information on unless exceptions, check .
You can also add the passthrough option to always yield next, even if no valid Authorization header was found:
点击(此处)折叠或打开
- app.use(jwt({ secret: 'shared-secret', passthrough: true }));
This lets downstream middleware make decisions based on whether ctx.state.user is set.
If you prefer to use another ctx key for the decoded data, just pass in key, like so:
点击(此处)折叠或打开
This makes the decoded data available as ctx.state.jwtdata.
You can specify audience and/or issuer as well:
点击(此处)折叠或打开
- app.use(jwt({ secret: 'shared-secret',
- audience: '',
- issuer: '' }));
If the JWT has an expiration (exp), it will be checked.
This module also support tokens signed with public/private key pairs. Instead of a secret, you can specify a Buffer with the public key:
点击(此处)折叠或打开
Note that koa-jwt exports the sign, verify and decode functions from the above module as a convenience.
点击(此处)折叠或打开
- $ npm install
- $ npm test
Stian Gryt?yr
This code is largely based on .
wemall地址:
代码来源: