Code Monkey home page Code Monkey logo

egg-jwt's People

Contributors

aa900031 avatar dependabot[bot] avatar hzgotb avatar jzleung avatar okoala avatar pythonfo avatar rccoder avatar seekcx avatar snyk-bot avatar solarhell avatar virtoolswebplayer avatar yi-man avatar zheng199512 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

egg-jwt's Issues

关于Bearer的问题

问一下,如果现在 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);
/**

  • rest api
    */
    router.post('/api/user/signin', controller.api.user.signin);
    router.post('/api/user/signup', controller.api.user.signup);

多路由前缀应该如何match呢

我现在需要在/wxauth和/pcauth路由下鉴权,在match中默认只能写string,function和正则,有没有数组配置的方式呢?如:

match: ['pcauth', wxauth],

返回类型怎么设置为json

现在返回的类型是html,请问怎么设置,
验证失败时,我在我的middleware中无法捕获到error,只能在app.on(error,callback)中才能捕获,但是此时好像拿不到ctx

jwt.sign 传入参数无效

如图
当我传入过期时间时,得不到预期的结果

image

而我直接使用jsonwebtoken库时时得到的结果与预期的一致。

image

猜测原因:因为看到之前有一个建议使用内部配置的Issues,已经mr进来了。可能是使用默认配置时将传入的配置覆盖了,导致传入失效。

egg-jwt 的正确使用姿势

我理想的操作步骤:

  1. 配置config
  2. plugin.js 开启插件
  3. router.js 里面针对哪个 url 想鉴权就加上 middleware

但我发现这样做了没用,访问的时候直接告诉我没有权限,然后我需要这么做:

  1. 登录接口调用 sign 生成 token, 返回给客户端(cookie或者客户端自行保存到localstore)
  2. 鉴权的请求收到时,调用 verify 进行解码 token, 然后进行验证

没能怎么搜到相关 demo, 不知道我的使用方式对不对。

match配置不工作

好像升级到依赖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, }; };

config设置match后无效

exports.jwt = {
  enable: true,
  ignore: '/login/login',
  secret: '123456',
  match: '/api/',
};

如上,想通过match自动启用app.jwt无效,是我配置错了吗

401返回内容

401返回内容能否自定义,现在默认返回的,不是很友好,怎么修改成返回自定义的内容

签名成功,并且请求时也有附带 token,但是后台一直报No authorization token was found

// 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

使用过滤黑白名单unless

看了源码并没有这个方法。

koa 实现

// 过滤不用jwt验证
app.use(jwt({secret: secret.sign}).unless({
    path: [
        /^\/api\/v1\/user/,
        /^\/api\/v1\/user\/login/]
}))

eggjs

ctx.app.jwt({secret: ctx.app.config.jwt.secret}).unless({
      path: [
        /^\/api\/v1\/user/,
        /^\/api\/v1\/user\/login/,
        /^\/signIn/,
      ]
      //数组中的路径不需要通过jwt验证
    })

app/middleware/jwt.js的作用是什么?

您好:
我想问一下,我有点看不懂下面的代码,还想请您解答~

'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');
});
为什么用异步的方法 不回调

assign is not a function

使用了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)

在Mac系统与Linux系统上调用jwt.sign()方法时报错

您好,我在使用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的位置就会被占用,从而报错。
不知道是我的用法不对,还是包有些问题,请您查看,希望能得到指导

请问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: '错误信息' }

typescript中 , app.jwt 作为中间件使用,类型不匹配报错了

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)

作为中间件使用时, 类型不匹配报错了

app.jwt 不可像 koa-jwt2 一样进行参数配置

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`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.