okoala / egg-jwt Goto Github PK
View Code? Open in Web Editor NEWJWT authentication plugin for egg
License: MIT License
JWT authentication plugin for egg
License: MIT License
问一下,如果现在 header 里的 Authorization 如果不是 "Bearer [token]" 的格式会报错,有没有办法设置前缀or手动解析 Authorization 中的数据?
在项目中添加了egg-jwt,配置了match匹配 /api/启用jwt,但是还是所有的路由都进行了身份校验。
eggjs版本2.x
配置:
config.jwt = {
secret: 'tttttt',
enable: true,
macth: '/api/',
};
路由:
router.get('/', controller.home.index);
/**
app.get("/success", "success.index"); // is setting in config.jwt.match
这个match是怎么用的?
我现在需要在/wxauth和/pcauth路由下鉴权,在match中默认只能写string,function和正则,有没有数组配置的方式呢?如:
match: ['pcauth', wxauth],
现在返回的类型是html,请问怎么设置,
验证失败时,我在我的middleware中无法捕获到error,只能在app.on(error,callback)中才能捕获,但是此时好像拿不到ctx
如题,看了相关代码 https://github.com/okoala/egg-jwt/blob/master/app/extend/application.js#L12-L14 只是简单挂载了一下 jsonwebtoken 的方法。
如何设置token有效时间?还是有默认值?
我理想的操作步骤:
plugin.js
开启插件router.js
里面针对哪个 url 想鉴权就加上 middleware但我发现这样做了没用,访问的时候直接告诉我没有权限,然后我需要这么做:
sign
生成 token, 返回给客户端(cookie或者客户端自行保存到localstore)verify
进行解码 token, 然后进行验证没能怎么搜到相关 demo, 不知道我的使用方式对不对。
app.jwt
這實例是 koa-jwt
,改成由 app/middleware
裡面再實例出來,應該比較符合框架邏輯吧?
如题, 那么设置app.config.jwt.secret 的意义是什么?
const jwtcode = app.jwt.sign({ uid: 1111 }, app.config.jwt.secret);
这样加工后返回的jwt code 可以在以下工具解密:
https://www.box3.cn/tools/jwt.html
好像升级到依赖koa-jwt2实现egg-jwt之后,match这个配置不工作了
是不是我使用得不对
我的config.default.js文件
module.exports = appInfo => { const config = {}; config.middleware = []; config.jwt = { secret: '123456', match: '/api/v2' }; const userConfig = {}; return { ...config, ...userConfig, }; };
exports.jwt = {
enable: true,
ignore: '/login/login',
secret: '123456',
match: '/api/',
};
如上,想通过match自动启用app.jwt无效,是我配置错了吗
Maybe need a mockJwt
funciton
401返回内容能否自定义,现在默认返回的,不是很友好,怎么修改成返回自定义的内容
// config/config.default.js
jwt: {
secret: 'Great4-M',
enable: true,
ignore: '/api/user/access/login',
}
// app/router.js
const { router, controller, middleware } = app;
const jwt = middleware.jwt(app.config.jwt);
router.get('/api/user', jwt, controller.user.index)
// Request Headers
GET /api/user?page=1&limit=20 HTTP/1.1
Host: 127.0.0.1:7001
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Sec-Fetch-Dest: empty
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7Il9pZCI6IjVlODYwNDk4ZjZmOTU4Nzk5MmU2NzdhMiJ9LCJleHAiOjE1ODY3MDQyMjgsImlhdCI6MTU4NjA5OTQyOH0.AX03Jfv5g9cAVv9apBb3gpNlY-lHMjkChmhG6TNNmJA
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
Origin: http://localhost:9528
Sec-Fetch-Site: cross-site
Sec-Fetch-Mode: cors
Referer: http://localhost:9528/dashboard
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6
// server log
2020-04-05 23:20:26,620 WARN 78099 [-/127.0.0.1/-/0ms GET /api/user?page=1&limit=20] nodejs.UnauthorizedError: No authorization token was found
at middleware (/node_modules/koa-jwt2/lib/index.js:89:15)
at fn (/node_modules/egg-core/lib/loader/mixin/middleware.js:112:12)
at dispatch (/node_modules/koa/node_modules/koa-compose/index.js:42:32)
at /node_modules/egg-development/app/middleware/egg_loader_trace.js:9:56
at dispatch (/node_modules/koa/node_modules/koa-compose/index.js:42:32)
at i18n (/node_modules/egg-i18n/app/middleware/i18n.js:13:12)
at dispatch (/node_modules/koa/node_modules/koa-compose/index.js:42:32)
at dispatch (/node_modules/egg-security/node_modules/koa-compose/index.js:42:32)
at dta (/node_modules/egg-security/lib/middlewares/dta.js:12:12)
at dispatch (/node_modules/egg-security/node_modules/koa-compose/index.js:42:32)
at xframe (/node_modules/egg-security/lib/middlewares/xframe.js:7:11)
at dispatch (/node_modules/egg-security/node_modules/koa-compose/index.js:42:32)
at xssProtection (/node_modules/egg-security/lib/middlewares/xssProtection.js:7:11)
at dispatch (/node_modules/egg-security/node_modules/koa-compose/index.js:42:32)
at nosniff (/node_modules/egg-security/lib/middlewares/nosniff.js:8:11)
at dispatch (/node_modules/egg-security/node_modules/koa-compose/index.js:42:32)
name: "UnauthorizedError"
message: "No authorization token was found"
code: "credentials_required"
status: 401
inner: {"message":"No authorization token was found"}
pid: 78099
看了源码并没有这个方法。
// 过滤不用jwt验证
app.use(jwt({secret: secret.sign}).unless({
path: [
/^\/api\/v1\/user/,
/^\/api\/v1\/user\/login/]
}))
ctx.app.jwt({secret: ctx.app.config.jwt.secret}).unless({
path: [
/^\/api\/v1\/user/,
/^\/api\/v1\/user\/login/,
/^\/signIn/,
]
//数组中的路径不需要通过jwt验证
})
this.ctx.state.user 是undefined的??
这是什么原因?
您好:
我想问一下,我有点看不懂下面的代码,还想请您解答~
'use strict';
const koajwt = require('koa-jwt2');
module.exports = options => {
return koajwt(options);
};
另外,我向你的index.d.ts提交了PR,您可以顺便看一下~
为什么还需要再有这个项目??
app.jwt.verify(ctx.request.header.authorization, app.config.jwt.secret, function(err, decoded) {
console.log('1');
});
为什么用异步的方法 不回调
不知道为啥出现mw is not a function?
this.app.jwt.decode(token) -> any or object ?
要怎么写才能在token错误或者没有token的时候,返回一个json
{
code:1,
success:false,
message:'token error'
}
ctx.state.user 可以提取到JWT编码的data,这里的原理是什么?
使用了egg-jwt的接口都会出错,http错误码500,错误信息为assign is not a function,引用方式应该没错的,麻烦帮忙看下是什么原因报错
// plugin.js
exports.jwt = {
enable: true,
package: 'egg-jwt',
};
// config.default.js
config.jwt = {
secret: '123456',
enable: true,
ignore: '/api/login',
};
HEADERS
host 127.0.0.1:7001
pragma no-cache
cache-control no-cache
authorization Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OTZhZmQwZGM3NjhmYjMzODhmMzk2YTIiLCJpYXQiOjE1MDAxODY5NzN9.wnlIngJSVekgYSGHoCzji-GV6kiWAlwZ2hwd0LAU86s
user-agent Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 appservice webview/100000
content-type application/json
accept */*
referer https://servicewechat.com/wx4228108b5fb42de1/devtools/page-frame.html
accept-encoding gzip, deflate, sdch
accept-language zh-CN,zh;q=0.8
2017-07-16 14:59:17,023 ERROR 7256 [-/127.0.0.1/-/5ms GET /api/user] nodejs.TypeError: assign is not a function
at Object.get locals [as locals] (C:\Users\F-loat\Desktop\ourauto\server\node_modules\egg\app\extend\context.js:154:22)
at Object.get state [as state] (C:\Users\F-loat\Desktop\ourauto\server\node_modules\egg\app\extend\context.js:176:16)
at jwt (C:\Users\F-loat\Desktop\ourauto\server\node_modules\koa-jwt\lib\index.js:29:23)
at Object.callFn (C:\Users\F-loat\Desktop\ourauto\server\node_modules\egg-core\lib\utils\index.js:45:15)
at callFn.next (<anonymous>)
at onFulfilled (C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:65:19)
at C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:54:5
at Promise (<anonymous>)
at Object.co (C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:50:10)
at Object.toPromise (C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:118:63)
at next (C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:99:29)
at onFulfilled (C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:69:7)
at C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:54:5
at Promise (<anonymous>)
at Object.co (C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:50:10)
at Object.toPromise (C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:118:63)
at next (C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:99:29)
at onFulfilled (C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:69:7)
at C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:54:5
at Promise (<anonymous>)
at Object.co (C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:50:10)
at Object.createPromise (C:\Users\F-loat\Desktop\ourauto\server\node_modules\co\index.js:30:15)
at Server.handleRequest (C:\Users\F-loat\Desktop\ourauto\server\node_modules\koa\lib\application.js:136:8)
at emitTwo (events.js:125:13)
at Server.emit (events.js:213:7)
at parserOnIncoming (_http_server.js:602:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
您好,我在使用egg-jwt时遇到了一个问题,在调用sign方法时,遇到了报错,根据提示我找到了sign.js 文件,并在里面发现了一些问题,特地来请教下。
我的config配置如下:
config.jwt = { secret: 'Great4-M', enable: true, // default is false match: '/jwt', // optional };
调用方法如下:
async apply(_id) { const {ctx} = this; return ctx.app.jwt.sign({ data: { _id: _id }, exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 7) }, ctx.app.config.jwt.secret); }
问题如下:
module.exports = function (payload, secretOrPrivateKey, options, callback) { console.log('payload',payload) console.log('secretOrPrivateKey',secretOrPrivateKey) console.log('options',options) console.log('callback',callback)
在Mac系统上执行这段代码时,打印的结果是
payload { data: { _id: 5b67b41d6b251132fa770c81 }, exp: 1534148604 } secretOrPrivateKey Great4-M options undefined callback undefined
而在Linux系统上打印时,缺变成了这样
payload { data: { name: '4444444' }, exp: 1534148370 } secretOrPrivateKey Great4-M options { '0': 'G', '1': 'r', '2': 'e', '3': 'a', '4': 't', '5': '4', '6': '-', '7': 'M' } callback undefined
观察发现,在Mac系统上时,secretOrPrivateKey 这个属性是调用sign方法时传入的,但是到了线上的linux系统时,就变成了从config里面自己读取的了,这样就会重复的出现,而options的位置就会被占用,从而报错。
不知道是我的用法不对,还是包有些问题,请您查看,希望能得到指导
interface EggAppConfig {
jwt: {
secret: string;
enable?: boolean;
sign?: SignOptions;
verify?: VerifyOptions;
};
}
建议在readme里加入verify的用法,这样对新手用户更友好。
使用(token, secret,callbback)
callback只能接收到一个参数,无法处理错误
控制台直接打印错误
{ JsonWebTokenError: 错误信息
at AsyncFunction.module.exports [as verify] (/data/webSite/wxtest.wuyunjiang.cn-server/node_modules/jsonwebtoken/verify.js:49:17)
at jwtAuth (/data/webSite/wxtest.wuyunjiang.cn-server/app/middleware/jwtAuth.js:6:13)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7) name: 'JsonWebTokenError', message: '错误信息' }
const jwt: {
sign(payload: string | object | Buffer, secretOrPrivateKey: string, options?: any, callback?: any): string;
verify(token: string, secretOrPrivateKey: string, options?: any, callback?: any): string;
decode(token: string): string;
}
No overload matches this call.
Overload 1 of 4, '(name: string, path: string | RegExp, ...middleware: Middleware<ParameterizedContext<any, Context & IRouterParamContext<any, Context>>>[]): Router<...>', gave the following error.
Argument of type '{ sign(payload: string | object | Buffer, secretOrPrivateKey: string, options?: any, callback?: any): string; verify(token: string, secretOrPrivateKey: string, options?: any, callback?: any): string; decode(token: string): string; }' is not assignable to parameter of type 'string | RegExp'.
Type '{ sign(payload: string | object | Buffer, secretOrPrivateKey: string, options?: any, callback?: any): string; verify(token: string, secretOrPrivateKey: string, options?: any, callback?: any): string; decode(token: string): string; }' is missing the following properties from type 'RegExp': exec, test, source, global, and 12 more.
Overload 2 of 4, '(path: string | RegExp | (string | RegExp)[], ...middleware: Middleware<ParameterizedContext<any, Context & IRouterParamContext<any, Context>>>[]): Router<...>', gave the following error.
Argument of type '{ sign(payload: string | object | Buffer, secretOrPrivateKey: string, options?: any, callback?: any): string; verify(token: string, secretOrPrivateKey: string, options?: any, callback?: any): string; decode(token: string): string; }' is not assignable to parameter of type 'Middleware<ParameterizedContext<any, Context & IRouterParamContext<any, Context>>>'.
Type '{ sign(payload: string | object | Buffer, secretOrPrivateKey: string, options?: any, callback?: any): string; verify(token: string, secretOrPrivateKey: string, options?: any, callback?: any): string; decode(token: string): string; }' provides no match for the signature '(context: ParameterizedContext<any, Context & IRouterParamContext<any, Context>>, next: Next): any'.
Overload 3 of 4, '(path: string | RegExp | (string | RegExp)[], middleware: Middleware<ParameterizedContext<unknown, unknown>>, routeHandler: Middleware<ParameterizedContext<any, Context & IRouterParamContext<...>>>): Router<...>', gave the following error.
Argument of type '{ sign(payload: string | object | Buffer, secretOrPrivateKey: string, options?: any, callback?: any): string; verify(token: string, secretOrPrivateKey: string, options?: any, callback?: any): string; decode(token: string): string; }' is not assignable to parameter of type 'Middleware<ParameterizedContext<unknown, unknown>>'.
Type '{ sign(payload: string | object | Buffer, secretOrPrivateKey: string, options?: any, callback?: any): string; verify(token: string, secretOrPrivateKey: string, options?: any, callback?: any): string; decode(token: string): string; }' provides no match for the signature '(context: ParameterizedContext<unknown, unknown>, next: Next): any'.ts(2769)
作为中间件使用时, 类型不匹配报错了
现在插件生成的token好像都是永久有效的 怎么去设置它的过期时间呢?
koa-jwt2 可以使用 ge('/', jwt(options), fn) 进行注销、未注册用户访问配置
egg-jwt 只能 ge('/', app.jwt, fn) , 使用 app.jwt(options) 出现报错
Error: get `/articles/:slug`: `middleware` must be a function, not `object`
config下没有match字段,会默认匹配所有路由路径
What if the token code expires, the user in use is pushed out, explain to me
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.