koa-jwt

Koa JWT authentication middleware.

koa-jwt

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 Koa (node.js) applications.

See this article for a good introduction.

Install

$ npm install koa-jwt

Usage

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.

Example

var koa = require('koa');
var jwt = require('koa-jwt');

var app = koa();

// Custom 401 handling if you don't want to expose koa-jwt errors to users
app.use(function *(next){
  try {
    yield next;
  } catch (err) {
    if (401 == err.status) {
      this.status = 401;
      this.body = 'Protected resource, use Authorization header to get access\n';
    } else {
      throw err;
    }
  }
});

// Unprotected middleware
app.use(function *(next){
  if (this.url.match(/^\/public/)) {
    this.body = 'unprotected\n';
  } else {
    yield next;
  }
});

// Middleware below this line is only reached if JWT token is valid
app.use(jwt({ secret: 'shared-secret' }));

// Protected middleware
app.use(function *(){
  if (this.url.match(/^\/api/)) {
    this.body = 'protected\n';
  }
});

app.listen(3000);

  

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

var koa = require('koa');
var jwt = require('koa-jwt');

var app = koa();

// Middleware below this line is only reached if JWT token is valid
// unless the URL starts with '/public'
app.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\/public/] }));

// Unprotected middleware
app.use(function *(next){
  if (this.url.match(/^\/public/)) {
    this.body = 'unprotected\n';
  } else {
    yield next;
  }
});

// Protected middleware
app.use(function *(){
  if (this.url.match(/^\/api/)) {
    this.body = 'protected\n';
  }
});

app.listen(3000);

  

For more information on unless exceptions, check koa-unless.

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:

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:

app.use(jwt({ secret:   'shared-secret',
              audience: 'http://myapi/protected',
              issuer:   'http://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:

 
var publicKey = fs.readFileSync('/path/to/public.pub');
app.use(jwt({ secret: publicKey }));

  

Related Modules

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

Tests

$ npm install
$ npm test

Author

Stian Grytøyr

Credits

This code is largely based on express-jwt.

Contributors

Licens

wemall  开源微商城 ,微信商城,商城源码,三级分销,微生鲜,微水果,微外卖,微订餐---专业的o2o系统

wemall地址:http://www.wemallshop.com

代码来源:http://js.koahub.com/home/feature/koa-jwt

 

KoaHub平台基于Node.js开发的Koa JWT认证插件代码信息详情的更多相关文章

  1. KoaHub平台基于Node.js开发的Koa 连接支付宝插件代码信息详情

    KoaHub平台基于Node.js开发的Koa 链接支付宝插件代码信息详情 easy-alipay alipay payment & notification APIs easy-alipay ...

  2. KoaHub平台基于Node.js开发的Koa router路由插件代码信息详情

    koa-router Router middleware for koa. Provides RESTful resource routing. koa-router       Router mid ...

  3. KoaHub平台基于Node.js开发的Koa EJS渲染插件代码信息详情

    koa-ejs ejs render middleware for koa koa-ejs Koa ejs view render middleware. support all feature of ...

  4. KoaHub平台基于Node.js开发的Koa的skip插件代码详情

    koahub-skip koahub skip middleware koahub skip Conditionally skip a middleware when a condition is m ...

  5. KoaHub平台基于Node.js开发的Koa的简单包装到请求库的类似接口

    co-request co-request promisify wrapper for request co-request Simple wrapper to the request library ...

  6. KoaHub平台基于Node.js开发的Koa的调试实用程序

    debug small debugging utility debug tiny node.js debugging utility modelled after node core's debugg ...

  7. KoaHub平台基于Node.js开发的Koa的连接MongoDB插件代码详情

    koa-mongo MongoDB middleware for koa, support connection pool. koa-mongo koa-mongo is a mongodb midd ...

  8. KoaHub平台基于Node.js开发的Koa的rewrite and index support插件代码详情

    koa-static-server Static file serving middleware for koa with directory, rewrite and index support k ...

  9. KoaHub平台基于Node.js开发的Koa的get/set session插件代码详情

    koa-session2 Middleware for Koa2 to get/set session use with custom stores such as Redis or mongodb ...

随机推荐

  1. 用 NodeJS 实现 BigPipe

    BigPipe 是 Facebook 开发的优化网页加载速度的技术.网上几乎没有用 node.js 实现的文章,实际上,不止于 node.js,BigPipe 用其他语言的实现在网上都很少见.以至于这 ...

  2. 移动设备应用程序中支持多个屏幕大小和 DPI 值

    支持多个屏幕大小和 DPI 值的指导原则 要部署独立于平台的应用程序,应了解不同的输出设备.设备可以具有不同的屏幕大小或分辨率以及不同的 DPI 值或密度. Flex 工程师 Jason SJ 在他的 ...

  3. MyBatis-Generator的配置说明和使用

    关于MyBatis: MyBatis Generator (MBG) 是一个Mybatis的代码生成器 MyBatis 和 iBATIS. 他可以生成Mybatis各个版本的代码,和iBATIS 2. ...

  4. saiku的源码包Bulid常见问题和jar包

    最近在做kylin+mondrian+saiku的二次开发的时候,Bulid saiku的源码出现了很多问题,基本上一大部分问题jar找不到问题,很多jar国内网站都找不到.这时候只有手动下载然后注册 ...

  5. android: activity切换之效果

    Activity是android应用的重要部分;为了提高用户的体验度,加了Activity之间切换的动画效果,现在介绍的一种切换动画: 是什么效果,大家自已动手测试一下便知道: 先看进入的动画: pa ...

  6. 从Chrome源码看浏览器的事件机制

    .aligncenter { clear: both; display: block; margin-left: auto; margin-right: auto } .crayon-line spa ...

  7. ubuntu ssh-keygen Permission denied

    ubuntu下生成github上的ssh keys,执行: ssh-keygen 直接执行: sudo chown user1:user1 /home/user1/.ssh -R 成功生成.

  8. .CN根域名被攻击至瘫痪,谁之过?

    2013-10-08 09:19 佚名 新浪科技 2013年8月25日凌晨,.CN域名凌晨出现大范围解析故障,经分析.CN的根域授权DNS全线故障,导致大面积.CN域名无法解析.事故造成大量以.cn和 ...

  9. 丢掉Mask遮罩,更好的圆形Image组件[Unity]

    写在前面 全文解析圆形Image组件的实现原理,取关键代码介绍算法细节,源码已经上传Github下载地址,欢迎下载试用. 一.Unity原生Image组件实现圆形图片的缺陷 Mask渲染消耗 许多游戏 ...

  10. 2732: [HNOI2012]射箭( 半平面交 )

    很久没写题解了= =,来水一发吧= = 首先这道题很明显就是求y=ax^2+bx的是否有值取,每一个式子都代表着两个半平面,然后直接半平面交就行了 借鉴了hzwer的代码,还是特别简洁的说 CODE: ...