KoaHub平台基于Node.js开发的Koa JWT认证插件代码信息详情
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
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
- jsonwebtoken — JSON Web Token signing and verification
Note that koa-jwt exports the sign
, verify
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-jwtKoaHub平台基于Node.js开发的Koa JWT认证插件代码信息详情的更多相关文章
- KoaHub平台基于Node.js开发的Koa 连接支付宝插件代码信息详情
KoaHub平台基于Node.js开发的Koa 链接支付宝插件代码信息详情 easy-alipay alipay payment & notification APIs easy-alipay ...
- KoaHub平台基于Node.js开发的Koa router路由插件代码信息详情
koa-router Router middleware for koa. Provides RESTful resource routing. koa-router Router mid ...
- KoaHub平台基于Node.js开发的Koa EJS渲染插件代码信息详情
koa-ejs ejs render middleware for koa koa-ejs Koa ejs view render middleware. support all feature of ...
- KoaHub平台基于Node.js开发的Koa的skip插件代码详情
koahub-skip koahub skip middleware koahub skip Conditionally skip a middleware when a condition is m ...
- KoaHub平台基于Node.js开发的Koa的简单包装到请求库的类似接口
co-request co-request promisify wrapper for request co-request Simple wrapper to the request library ...
- KoaHub平台基于Node.js开发的Koa的调试实用程序
debug small debugging utility debug tiny node.js debugging utility modelled after node core's debugg ...
- KoaHub平台基于Node.js开发的Koa的连接MongoDB插件代码详情
koa-mongo MongoDB middleware for koa, support connection pool. koa-mongo koa-mongo is a mongodb midd ...
- KoaHub平台基于Node.js开发的Koa的rewrite and index support插件代码详情
koa-static-server Static file serving middleware for koa with directory, rewrite and index support k ...
- 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 ...
随机推荐
- dbf导入sqlserver的方法
1. dbf导出为foxpro2.x. 2.打开excel,点击打开,选择dbase文件,选中第一步保存的文件. 3.另存为xls格式 4.使用sql的dts导入xls.
- Cocos2d-x 多分辨率支持
最近遇到多分辨率支持问题,所以查了一些资料.将一些收获共享一下,以便自己和其他需要的朋友日后参考. 如果我要建立一个cocos2d-x项目,我的目标是支持iphone3G( 480, 320 ),ip ...
- C++实现具有基本功能的智能指针
C++中的智能指针实际上是代理模式与RAII的结合. 自定义unique_ptr,主要是release()和reset().代码如下. #include <iostream> using ...
- spring EL表达式,null-safe表达式
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://ww ...
- Android 自定义Activity栈对Activity统一管理
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6307239.html public class AppManager { private static St ...
- Java中的==、equals、hasCode方法
== java 的数据类型分为“基本数据类型” 和“引用数据类型”在基本数据类型的比较中,== 比的就是基本数据类型变量中所保存的值在引用数据类型的比较中,== 才比较的是变量所指向的对象的地址. e ...
- 大大维的游戏机计划3--2048v1
前几天由于忙着过年串门,游戏机的计划搁置了几天.这两天终于空出了一块时间,抽空写了2048. 由于笔者前面自制了一个类似2048的游戏,所以写起来也算是轻车熟路,花了两个晚上也就差不多了. 废话少说, ...
- Javascript日期格式化指定格式的字符串实现
代码部分 TypeScript /** * format a Date object * 将 Date 转化为指定格式的String * @param {Date} date 源日期对象 * @par ...
- PHP标准库(SPL)- SplDoublyLinkedList类(双向链表)
class SplDoublyLinkedList implements Iterator, Traversable, Countable, ArrayAccess { const IT_MODE_L ...
- Swift 2.0 UItableView 的简单使用
在IOS开发中,UItableView 的使用真的是最常见最普通的了,现在在自学swift 今天也是这用Swift 写了写 UItableview的使用,还有一些经常出错的地方.下面我先把整个控制器的 ...