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. HDU-1232-畅通工程(并查集)

    题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1232考察并查集,(最小生成树)题目很简单用k记录树根的个数,k-1就是还需要建设的路 #include& ...

  2. MYBATIS 无效的列类型: 1111

    查询的时候竟然也会报错,如果参数是数字,需要加上jdbcType 在xml中加上 t.chart_id = #{chartId,jdbcType=DECIMAL}

  3. PariticalFilter在MFC上的运行,源代码公开

    由于项目需要,进行过一段时间的 PariticalFilter 研究.主要的工作就是将网络上的Console代码和Mfc融合在一起,并且添加了Mfc端的控制功能.       程序还有不完善的地方,现 ...

  4. Nancy简单实战之NancyMusicStore(四):实现购物车

    前言 上一篇,我们完成了商品的详情和商品的管理,这一篇我们来完成最后的一个购物车功能. 购物车,不外乎这几个功能:添加商品到购物车,删除购物车中的商品,对购物车中的商品进行结算. MVC MusicS ...

  5. CodeForces 327C

    Magic Five Time Limit:1000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u Submit  ...

  6. MyEclipse+Tomcat开发Web项目时修改内容不能及时显示问题解决方法

    问题描述:MyEclipse+Tomcat开发Web项目时,修改的内容不能从浏览器即时显示 原因:缓存问题 解决方法:开启Tomcat的Debug模式 点击如下图红色标记中的图标(Restart th ...

  7. LinkedList底层实现,及其数据结构实现。

    LinkedList底层的实现基于双向表 prev data next next指向下一个node的地址.prev指向上一个node. 这里的代码是LinkedList类的源码. private st ...

  8. 安卓UDP通信

    功能: 实现了单次一发一收: import java.net.*; import java.io.*; public class udpRecv { /* * 创建UDP传输的接收端 * 1.建立ud ...

  9. JavaScript中几个相似方法对比

    一.substring与substr   substring substr 概述 返回字符串两个索引之间(或到字符串末尾)的子串 返回字符串从指定位置开始到指定长度的子串 语法 参数 indexSta ...

  10. Monkey实例测试

    三.Monkey实例测试 Windows下(注:2-4步是为了查看我们可以测试哪些应用程序包,可省略): 1. 通过eclipse启动一个Android的emulator或者2 2. 在命令行中输入: ...