Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何使用jwt鉴权? #1495

Open
TangJinJian opened this issue Jun 24, 2020 · 1 comment
Open

如何使用jwt鉴权? #1495

TangJinJian opened this issue Jun 24, 2020 · 1 comment

Comments

@TangJinJian
Copy link

如何使用jwt鉴权?

环境

OS Platform: Windows 10

Node.js Version: v12.18.1

ThinkJS Version: 3.0.0

更多描述

我阅读了《ThinkJS JWT 鉴权实践》,但是里面使用到了装饰器,但是这个特性并不能直接使用,所以我希望使用其它方式判断权限。

另外,我发现在thinkjs中,添加中间件koa-jwt,貌似不起作用,如下实例:

const path = require('path');
const jwt = require('koa-jwt');
const { think } = require('thinkjs');
const isDev = think.env === 'development';

module.exports = [
  {
    handle: 'meta',
    options: {
      logRequest: isDev,
      sendResponseTime: isDev
    }
  },
  {
    handle: 'resource',
    enable: isDev,
    options: {
      root: path.join(think.ROOT_PATH, 'www'),
      publicPath: /^\/(static|favicon\.ico)/
    }
  },
  // {
  //   handle: 'trace',
  //   enable: !think.isCli,
  //   options: {
  //     debug: isDev
  //   }
  // },
  {
    handle: 'payload',
    options: {
      keepExtensions: true,
      limit: '5mb'
    }
  },
  {
    handle: 'token-error',
    options: {}
  },
  {
    handle: jwt,
    options: {
      secret: think.config('jwt').secret
    }
  },
  {
    handle: 'router',
    options: {}
  },
  'logic',
  'controller'
];
@lizheming
Copy link
Contributor

装饰器只是一种语法糖,本质上

class a {
  @checkAuth
  aAction() {}
}

基本上就等于

class a {
  aAction() {}
}
a.prototype.aAction = checkAuth(a.prototype.aAction);

所以重要的不是装饰器,装饰器只是提供了一个在执行 Action 之前去做权限校验的一个时机而已。重要的是你需要去理解 checkAuth 里面干了什么事情,本质上里面就是根据用户信息重新生成 token 并更新 cookie。至于这个时机,你只要找一个 Action 执行之前的时机即可,__before() 或者 logic 中执行都是可以的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants