3.16.1 • Published 12 days ago

@midwayjs/passport v3.16.1

Weekly downloads
-
License
MIT
Repository
-
Last release
12 days ago

@midwayjs/passport

身份验证是大多数Web应用程序的重要组成部分。因此Midway封装了目前Nodejs中最流行的Passport库。 Passport是通过称为策略的可扩展插件进行身份验证请求。Passport 不挂载路由或假设任何特定的数据库,这最大限度地提高了灵活性并允许开发人员做出应用程序级别的决策。

准备

  1. 安装 npm i @midwayjs/passport 和相关依赖
$ npm i @midwayjs/passport passport --save
$ npm i @types/passport --save-dev
  1. 如果有需要的话,开启相对应框架的 bodyparser,session

使用

这里我们以本地认证,和Jwt作为演示。

首先

// configuration.ts

import { join } from 'path';
import * as jwt from '@midwayjs/jwt';
import { ILifeCycle,} from '@midwayjs/core';
import { Configuration } from '@midwayjs/core';
import * as passport from '@midwayjs/passport';

@Configuration({
  imports: [
    jwt,
    passport,
  ],
  importConfigs: [join(__dirname, './config')],
  conflictCheck: true,
})
export class ContainerLifeCycle implements ILifeCycle {}

e.g. 本地

我们可以通过@CustomStrategy和派生PassportStrategy来自启动一个策略。通过 validate 钩子来获取有效负载,并且此函数必须有返回值,其参数并不明确,可以参考对应的Strategy或者通过展开符打印查看。

// local-strategy.ts

import { CustomStrategy, PassportStrategy } from '@midwayjs/passport';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/orm';
import { UserEntity } from './user';
import * as bcrypt from 'bcrypt';

@CustomStrategy()
export class LocalStrategy extends PassportStrategy(Strategy) {
  @InjectEntityModel(UserEntity)
  userModel: Repository<UserEntity>;

  // 策略的验证
  async validate(username, password) {
    const user = await this.userModel.findOne({ username });
    if (await bcrypt.compare(password, user.password)) {
      throw new Error('error password ' + username);
    }

    return {
      username,
      password,
    };
  }

  // 当前策略的参数
  getStrategyOptions(): any {
    return {};
  }
}

使用派生PassportMiddleware出一个中间件。

// local-middleware.ts

import { Inject, Provide } from '@midwayjs/core';
import { PassportMiddleware } from '@midwayjs/passport';
import { Context } from '@midwayjs/express';

@Provide()
export class LocalPassportMiddleware extends PassportMiddleware(LocalStrategy) {
  // 设置 AuthenticateOptions
  getAuthenticateOptions(): Promise<passport.AuthenticateOptions> | passport.AuthenticateOptions {
    return {
      failureRedirect: '/login',
      presetProperty: 'user'
    };
  }
}
// controller.ts

import { Provide, Post, Inject, Controller } from '@midwayjs/core';

@Provide()
@Controller('/')
export class LocalController {

  @Post('/passport/local', { middleware: [LocalPassportMiddleware] })
  async localPassport() {
    console.log('local user: ', this.ctx.req.user);
    return this.ctx.req.user;
  }
}

使用curl 模拟一次请求。

curl -X POST http://localhost:7001/passport/local -d '{"username": "demo", "password": "1234"}' -H "Content-Type: application/json"

结果 {"username": "demo", "password": "1234"}

e.g. Jwt

首先你需要安装npm i @midwayjs/jwt,然后在 config.ts 中配置。PS. 默认未加密,请不要吧敏感信息存放在payload中。

export const jwt = {
	secret: 'xxxxxxxxxxxxxx', // fs.readFileSync('xxxxx.key')
  expiresIn: '2d'   // https://github.com/vercel/ms
}
// strategy/jwt-strategy.ts

import { CustomStrategy, PassportStrategy } from '@midwayjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';

@CustomStrategy()
export class JwtStrategy extends PassportStrategy(
  Strategy,
  'jwt'
) {
  @Config('jwt')
  jwtConfig;

  async validate(payload) {
    return payload;
  }

  getStrategyOptions(): any {
    return {
      secretOrKey: this.jwtConfig.secret,
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    };
  }
}
// jwt-middleware.ts

import { Provide } from '@midwayjs/core';
import { PassportMiddleware } from '@midwayjs/passport';
import { JwtStrategy } from './strategy/jwt-strategy';

@Provide()
export class JwtPassportMiddleware extends PassportMiddleware(JwtStrategy) {
  getAuthenticateOptions(): Promise<passport.AuthenticateOptions> | passport.AuthenticateOptions {
    return {};
  }
}
import { Provide, Post, Inject } from '@midwayjs/core';
import { Controller, Post } from '@midwayjs/core';
import { Jwt } from '@midwayjs/jwt';

@Provide()
@Controller('/')
export class JwtController {

  @Inject()
  jwt: Jwt;

  @Inject()
  ctx: any;

  @Post('/passport/jwt', { middleware: [JwtPassportMiddleware] })
  async jwtPassport() {
    console.log('jwt user: ', this.ctx.req.user);
    return this.ctx.req.user;
  }

  @Post('/jwt')
  async genJwt() {
    return {
      t: await this.jwt.sign({ msg: 'Hello Midway' }),
    };
  }
}

使用curl模拟请求

curl -X POST http://127.0.0.1:7001/jwt

结果 {"t": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}

curl http://127.0.0.1:7001/passport/jwt -H "Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

结果 {"msg": "Hello Midway","iat": 1635468727,"exp": 1635468827}

自定义其他策略

@midwayjs/passport支持自定义其他策略,这里以github oauth为例。 首先 npm i passport-github,之后编写如下代码:

// github-strategy.ts

import { CustomStrategy, PassportStrategy } from '@midwayjs/passport';
import { Strategy, StrategyOptions } from 'passport-github';

const GITHUB_CLIENT_ID = 'xxxxxx', GITHUB_CLIENT_SECRET = 'xxxxxxxx';

@CustomStrategy()
export class GithubStrategy extends PassportStrategy(Strategy, 'github') {
  async validate(...payload) {
    return payload;
  }
  getStrategyOptions() {
    return {
      clientID: GITHUB_CLIENT_ID,
      clientSecret: GITHUB_CLIENT_SECRET,
      callbackURL: 'https://127.0.0.1:7001/auth/github/cb'
    };
  }
}
// github-middleware.ts

import { PassportMiddleware } from '@midwayjs/passport';

@Provide()
export class GithubPassportMiddleware extends PassportMiddleware {
}
// controller.ts

import { Provide, Get, Inject } from '@midwayjs/core';

@Provide()
@Controller('/oauth')
export class AuthController {
  @Inject()
  ctx: any;

  @Get('/github', { middleware: [GithubPassportMiddleware] })
  async githubOAuth() {}

  @Get('/github/cb', { middleware: [GithubPassportMiddleware] })
  async githubOAuthCallback() {
    return this.ctx.req.user;
  }
}
3.16.1

12 days ago

3.16.0

15 days ago

3.15.11

26 days ago

3.15.10

1 month ago

3.15.8

1 month ago

3.15.7

2 months ago

3.15.6

2 months ago

3.15.2

2 months ago

3.15.1

3 months ago

3.15.0

3 months ago

3.14.12

3 months ago

3.14.11

3 months ago

3.14.10

4 months ago

3.14.7

4 months ago

3.14.4

4 months ago

3.14.3

4 months ago

3.14.0

4 months ago

3.13.9

5 months ago

3.13.8

5 months ago

3.13.7

5 months ago

3.13.6

5 months ago

3.13.5

6 months ago

3.13.2

6 months ago

3.13.1

6 months ago

3.13.4

6 months ago

3.13.3

6 months ago

3.12.1

9 months ago

3.12.0

9 months ago

3.12.10

7 months ago

3.13.0

6 months ago

3.12.3

9 months ago

3.12.2

9 months ago

3.12.7

7 months ago

3.12.8

7 months ago

3.11.12

11 months ago

3.11.15

10 months ago

3.11.9

12 months ago

3.11.11

11 months ago

3.11.10

12 months ago

3.10.15

1 year ago

3.10.16

1 year ago

3.11.4

1 year ago

3.11.3

1 year ago

3.11.6

1 year ago

3.11.5

1 year ago

3.11.0

1 year ago

3.11.1

1 year ago

3.10.10

1 year ago

3.10.13

1 year ago

3.10.11

1 year ago

3.10.5

1 year ago

3.10.4

1 year ago

3.10.7

1 year ago

3.10.6

1 year ago

3.10.9

1 year ago

3.10.1

1 year ago

3.10.0

1 year ago

3.10.3

1 year ago

3.9.9

1 year ago

3.9.0

1 year ago

3.8.0

2 years ago

3.7.3

2 years ago

3.6.0

2 years ago

3.7.1

2 years ago

3.7.0

2 years ago

3.4.13

2 years ago

3.5.3

2 years ago

3.5.1

2 years ago

3.5.0

2 years ago

3.4.0-beta.7

2 years ago

3.4.0-beta.6

2 years ago

3.4.0-beta.11

2 years ago

3.4.0-beta.5

2 years ago

3.4.0-beta.12

2 years ago

3.4.0-beta.4

2 years ago

3.4.0-beta.10

2 years ago

3.4.0-beta.9

2 years ago

3.4.0-beta.8

2 years ago

3.4.0-beta.3

2 years ago

3.4.0-beta.2

2 years ago

3.4.0-beta.1

2 years ago

3.4.0

2 years ago

3.4.4

2 years ago

3.4.3

2 years ago

3.4.1

2 years ago

3.4.10

2 years ago

3.4.11

2 years ago

3.4.12

2 years ago

3.4.7

2 years ago

3.4.6

2 years ago

3.4.9

2 years ago

3.3.9

2 years ago

3.3.6

2 years ago

3.3.13

2 years ago

3.3.11

2 years ago

3.1.7-alpha.0

2 years ago

3.2.2

2 years ago

3.2.1

2 years ago

3.2.0

2 years ago

3.3.1

2 years ago

3.3.0

2 years ago

3.3.5

2 years ago

3.3.4

2 years ago

3.1.6

2 years ago

3.3.3

2 years ago

3.3.2

2 years ago

3.1.3

2 years ago

3.1.2

2 years ago

3.0.13

2 years ago

3.1.1

2 years ago

3.1.0

2 years ago

2.14.7

2 years ago

3.1.5

2 years ago

3.1.4

2 years ago

3.0.9

2 years ago

3.0.4

2 years ago

3.0.3

2 years ago

3.0.10

2 years ago

3.0.2

2 years ago

3.0.11

2 years ago

3.0.1

2 years ago

3.0.8

2 years ago

3.0.7

2 years ago

3.0.6

2 years ago

3.0.5

2 years ago

2.14.6

2 years ago

2.14.4

2 years ago

3.0.0

2 years ago

2.14.2

2 years ago

3.0.4-beta.1

2 years ago

3.0.0-beta.12

2 years ago

3.0.0-beta.13

2 years ago

3.0.0-beta.14

2 years ago

3.0.0-beta.15

2 years ago

3.0.0-beta.16

2 years ago

3.0.0-beta.17

2 years ago

3.0.0-beta.11

2 years ago

3.0.0-beta.10

2 years ago

3.0.0-beta.9

2 years ago

3.0.0-beta.8

2 years ago

2.14.1

2 years ago

2.14.0

2 years ago

2.13.3

2 years ago