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. javascript window.confirm确认 取消对话框实现代码小结

    本文章讲述的三种都是基于了javascript confirm提示确认框的做法了,只是在不同的地方写哦,有需要的同学可参考一下   confirm() 方法 confirm() 方法用于显示一个带有指 ...

  2. easyUI resizable组件使用

    easyUI resizable组件使用: <!DOCTYPE html> <html lang="en"> <head> <meta c ...

  3. HDU5918(KMP)

    Sequence I Time Limit: 3000/1500 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total ...

  4. BZOJ2002(分块)

    Bounce 弹飞绵羊 Time Limit:10000MS     Memory Limit:265216KB     64bit IO Format:%lld & %llu Submit  ...

  5. C/C++中的联合体

    C/C++中的联合体 利用union可以用相同的存储空间存储不同型别的数据类型,从而节省内存空间.当访问其内成员时可用"."和"->"来直接访问. 当多个 ...

  6. IIS7上搭建网站的基本方法(系统推荐的安全方案)

    1.创建的程序池命名默认为网站名称,程序池的标识采用默认的ApplicationPoolIdentity,这个会自动生成虚拟的用户,系统推荐的安全方案: 2.网站右键 基本设置 --> 连接为 ...

  7. 循环语句——for语句

    一.for语句结构:for (初始化表达式; 循环条件表达式 ;循环后的操作表达式 ) { 执行语句: } 循环条件表达式,必须是true或false 示例: class ForDemo { publ ...

  8. Java中Redis简单入门

    Redis是一个开源的,先进的 key-value 存储可用于构建高性能,可扩展的 Web 应用程序的解决方案. Redis官方网网站是:http://www.redis.io/,如下: Redis ...

  9. asp.net core mvc权限控制:权限控制介绍

    在进行业务软件开发的时候,都会涉及到权限控制的问题,asp.net core mvc提供了相关特性. 在具体介绍使用方法前,我们需要先了解几个概念: 1,claim:英文翻译过来是声明的意思,一个cl ...

  10. 特殊的string类型

    1.前言 string是属于引用类型的,这个大家都知道吧?但是平常在使用的过程中,发现它还是拥有一些值类型的特征的,这到底是为什么呢? 原因就是.Net考虑到假如大量的操作string对象的时候,大量 ...