Chinaunix首页 | 论坛 | 博客
  • 博客访问: 53169
  • 博文数量: 48
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 260
  • 用 户 组: 普通用户
  • 注册时间: 2016-07-12 11:48
文章分类
文章存档

2016年(48)

我的朋友

分类: Web开发

2016-10-14 17:46:25

koa-jwt

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.


点击(此处)折叠或打开

  1. $ npm install koa-jwt


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.

 

点击(此处)折叠或打开

  1. var koa = require('koa');
  2. var jwt = require('koa-jwt');
  3.  
  4. var app = koa();
  5.  
  6. // Custom 401 handling if you don't want to expose koa-jwt errors to users
  7. app.use(function *(next){
  8.   try {
  9.     yield next;
  10.   } catch (err) {
  11.     if (401 == err.status) {
  12.       this.status = 401;
  13.       this.body = 'Protected resource, use Authorization header to get access\n';
  14.     } else {
  15.       throw err;
  16.     }
  17.   }
  18. });
  19.  
  20. // Unprotected middleware
  21. app.use(function *(next){
  22.   if (this.url.match(/^\/public/)) {
  23.     this.body = 'unprotected\n';
  24.   } else {
  25.     yield next;
  26.   }
  27. });
  28.  
  29. // Middleware below this line is only reached if JWT token is valid
  30. app.use(jwt({ secret: 'shared-secret' }));
  31.  
  32. // Protected middleware
  33. app.use(function *(){
  34.   if (this.url.match(/^\/api/)) {
  35.     this.body = 'protected\n';
  36.   }
  37. });
  38.  
  39. app.listen(3000);

Alternatively you can conditionally run the jwt middleware under certain conditions:

 

点击(此处)折叠或打开

  1. var koa = require('koa');
  2. var jwt = require('koa-jwt');
  3.  
  4. var app = koa();
  5.  
  6. // Middleware below this line is only reached if JWT token is valid
  7. // unless the URL starts with '/public'
  8. app.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public/] }));
  9.  
  10. // Unprotected middleware
  11. app.use(function *(next){
  12.   if (this.url.match(/^\/public/)) {
  13.     this.body = 'unprotected\n';
  14.   } else {
  15.     yield next;
  16.   }
  17. });
  18.  
  19. // Protected middleware
  20. app.use(function *(){
  21.   if (this.url.match(/^\/api/)) {
  22.     this.body = 'protected\n';
  23.   }
  24. });
  25.  
  26. app.listen(3000);

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:

			

点击(此处)折叠或打开

  1. 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:

点击(此处)折叠或打开

  1. app.use(jwt({ secret: 'shared-secret', key: 'jwtdata' }));

This makes the decoded data available as ctx.state.jwtdata.

You can specify audience and/or issuer as well:

			

点击(此处)折叠或打开

  1. app.use(jwt({ secret: 'shared-secret',
  2.               audience: '',
  3.               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:

点击(此处)折叠或打开

  1. var publicKey = fs.readFileSync('/path/to/public.pub');
  2. app.use(jwt({ secret: publicKey }));
  •  — JSON Web Token signing and verification

Note that koa-jwt exports the sign, verify and decode functions from the above module as a convenience.

	

点击(此处)折叠或打开

  1. $ npm install
  2. $ npm test

Stian Gryt?yr

This code is largely based on .

wemall地址:

 

代码来源:
 
阅读(654) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~