三、Midway 接口安全認(rèn)證

閱讀本文前,需要提前閱讀前置內(nèi)容:

一、Midway 增刪改查
二、Midway 增刪改查的封裝及工具類
三、Midway 接口安全認(rèn)證
四、Midway 集成 Swagger 以及支持JWT bearer
五、Midway 中環(huán)境變量的使用

樣例源碼
DEMO LIVE

很多時(shí)候,后端接口需要登錄后才能進(jìn)行訪問,甚至有的接口需要擁有相應(yīng)的權(quán)限才能訪問。
這里實(shí)現(xiàn)bearer驗(yàn)證方式(bearerFormat 為 JWT)。

安裝JWT組件

>npm i @midwayjs/jwt@3 --save
>npm i @types/jsonwebtoken --save-dev

安裝完后package.json文件中會(huì)多出如下配置

{
  "dependencies": {
    "@midwayjs/jwt": "^3.3.11"
  },
  "devDependencies": {
    "@types/jsonwebtoken": "^8.5.8"
  }
}

添加JWT配置

  • 修改src/config/config.default.ts,添加如下內(nèi)容;
// src/config/config.default.ts
jwt: {
  secret: 'setscrew',
  expiresIn: 60 * 60 * 24,
}
  • 注冊JWT組件;
// src/configuration.ts
import * as jwt from '@midwayjs/jwt';

@Configuration({
  imports: [
    jwt,
    //...
  ],
})
export class ContainerLifeCycle {
    //...
}

關(guān)于JWT的詳細(xì)使用文檔,見:http://www.midwayjs.org/docs/extensions/jwt

安裝Redis組件

>npm i @midwayjs/redis@3 --save
>npm i @types/ioredis --save-dev

安裝完后package.json文件中會(huì)多出如下配置

{
  "dependencies": {
    "@midwayjs/redis": "^3.0.0"
  },
  "devDependencies": {
    "@types/ioredis": "^4.28.7"
  }
}

注冊Redis組件

// src/configuration.ts
import * as redis from '@midwayjs/redis';

@Configuration({
  imports: [
    redis,
    // ...
  ],
})
export class ContainerLifeCycle {
    // ...
}

添加配置

修改src/config/config.default.ts,添加如下內(nèi)容:

添加Redis配置

// src/config/config.default.ts
redis: {
  client: {
    host: 127.0.0.1,
    port: 6379,
    db: 0,
  },
}

關(guān)于Redis的詳細(xì)使用文檔,見:http://www.midwayjs.org/docs/extensions/redis

添加安全攔截配置

// src/config/config.default.ts
app: {
  security: {
    prefix: '/api',         # 指定已/api開頭的接口地址需要攔截
    ignore: ['/api/login'], # 指定該接口地址,不需要攔截
  },
}

添加接口安全攔截中間件

添加常量定義

// src/common/Constant.ts
export class Constant {
  // 登陸驗(yàn)證時(shí),緩存用戶登陸狀態(tài)KEY的前綴
  static TOKEM = 'TOKEN';
}

添加用戶訪問上下文類

// src/common/UserContext.ts
/**
 * 登陸后存儲(chǔ)訪問上下文的狀態(tài)數(shù)據(jù),同時(shí)也會(huì)存在redis緩存中
 */
export class UserContext {
  userId: number;
  username: string;
  phoneNum: string;
  constructor(userId: number, username: string, phoneNum: string) {
    this.userId = userId;
    this.username = username;
    this.phoneNum = phoneNum;
  }
}

新增或者編輯src/interface.ts,將UserContext注冊到ApplecationContext

// src/interface.ts
import '@midwayjs/core';
import { UserContext } from './common/UserContext';

declare module '@midwayjs/core' {
  interface Context {
    userContext: UserContext;
  }
}

新增中間件src/middleware/security.middleware.ts

// src/middleware/security.middleware.ts
import { Config, Inject, Middleware } from '@midwayjs/decorator';
import { Context, NextFunction } from '@midwayjs/koa';
import { httpError } from '@midwayjs/core';
import { JwtService } from '@midwayjs/jwt';
import { UserContext } from '../common/UserContext';
import { RedisService } from '@midwayjs/redis';
import { Constant } from '../common/Constant';

/**
 * 安全驗(yàn)證
 */
@Middleware()
export class SecurityMiddleware {

  @Inject()
  jwtUtil: JwtService;

  @Inject()
  cacheUtil: RedisService;

  @Config('app.security')
  securityConfig;

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      if (!ctx.headers['authorization']) {
        throw new httpError.UnauthorizedError('缺少憑證');
      }
      const parts = ctx.get('authorization').trim().split(' ');
      if (parts.length !== 2) {
        throw new httpError.UnauthorizedError('無效的憑證');
      }
      const [scheme, token] = parts;
      if (!/^Bearer$/i.test(scheme)) {
        throw new httpError.UnauthorizedError('缺少Bearer');
      }
      // 驗(yàn)證token,過期會(huì)拋出異常
      const jwt = await this.jwtUtil.verify(token, { complete: true });
      // jwt中存儲(chǔ)的user信息
      const payload = jwt['payload'];
      const key = Constant.TOKEM + ':' + payload.userId + ':' + token;
      const ucStr = await this.cacheUtil.get(key);
      // 服務(wù)器端緩存中存儲(chǔ)的user信息
      const uc: UserContext = JSON.parse(ucStr);
      if (payload.username !== uc.username) {
        throw new httpError.UnauthorizedError('無效的憑證');
      }
      // 存儲(chǔ)到訪問上下文中
      ctx.userContext = uc;
      return next();
    };
  }

  public match(ctx: Context): boolean {
    const { path } = ctx;
    const { prefix, ignore } = this.securityConfig;
    const exist = ignore.find((item) => {
      return item.match(path);
    });
    return path.indexOf(prefix) === 0 && !exist;
  }

  public static getName(): string {
    return 'SECURITY';
  }

}
  • @Config('app.security')裝飾類,指定加載配置文件src/config/config.**.ts中對應(yīng)的配置信息;
  • 使用JwtService進(jìn)行JWT編碼校驗(yàn);

jwt token將用戶信息編碼在token中,解碼后可以獲取對應(yīng)用戶數(shù)據(jù),通常情況下,不需要存儲(chǔ)到redis中;
但是有個(gè)缺點(diǎn)就是,不能人為控制分發(fā)出去的token失效。所以,有時(shí)人們會(huì)使用緩存中的用戶信息;
這里使用了JWT+Redis的方式,是為了演示兩種做法;

注冊中間件

// src/configuration.ts
this.app.useMiddleware([SecurityMiddleware, FormatMiddleware, ReportMiddleware]);

添加登陸接口

  • 添加DTO;
// src/api/dto/CommonDTO.ts
export class LoginDTO {
  username: string;
  password: string;
}
  • 添加VO;
// src/api/vo/CommonVO.ts
export class LoginVO {
  accessToken: string;
  expiresIn: number;
}
  • 修改src/service/user.service.ts,添加通過用戶名查找用戶接口;
import { Provide } from '@midwayjs/decorator';
import { User } from '../eneity/user';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { BaseService } from '../common/BaseService';

@Provide()
export class UserService extends BaseService<User> {

  @InjectEntityModel(User)
  model: Repository<User>;

  getModel(): Repository<User> {
    return this.model;
  }

  async findByUsername(username: string): Promise<User> {
    return this.model.findOne({ where: { username } });
  }

}
  • 添加Controllersrc/controller/common.controller.ts;
// src/controller/common.controller.ts
import { Body, Config, Controller, Inject, Post } from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import { UserService } from '../service/user.service';
import { RedisService } from '@midwayjs/redis';
import { LoginDTO } from '../api/dto/CommonDTO';
import { LoginVO } from '../api/vo/CommonVO';
import { SnowflakeIdGenerate } from '../utils/Snowflake';
import { JwtService } from '@midwayjs/jwt';
import { Assert } from '../common/Assert';
import { ErrorCode } from '../common/ErrorCode';
import { UserContext } from '../common/UserContext';
import { Constant } from '../common/Constant';
import { ILogger } from '@midwayjs/core';
import { decrypt } from '../utils/PasswordEncoder';
import { Validate } from '@midwayjs/validate';
import { ApiResponse, ApiTags } from '@midwayjs/swagger';

@ApiTags(['common'])
@Controller('/api')
export class CommonController {

  @Inject()
  logger: ILogger;

  @Inject()
  ctx: Context;

  @Inject()
  userService: UserService;

  @Inject()
  cacheUtil: RedisService;

  @Inject()
  jwtUtil: JwtService;

  @Inject()
  idGenerate: SnowflakeIdGenerate;

  @Config('jwt')
  jwtConfig;

  @ApiResponse({ type: LoginVO })
  @Validate()
  @Post('/login', { description: '登陸' })
  async login(@Body() body: LoginDTO): Promise<LoginVO> {
    const user = await this.userService.findByUsername(body.username);
    Assert.notNull(user, ErrorCode.UN_ERROR, '用戶名或者密碼錯(cuò)誤');
    const flag = decrypt(body.password, user.password);
    Assert.isTrue(flag, ErrorCode.UN_ERROR, '用戶名或者密碼錯(cuò)誤');
    const uc: UserContext = new UserContext(user.id, user.username, user.phoneNum);
    const at = await this.jwtUtil.sign({ ...uc });
    const key = Constant.TOKEM + ':' + user.id + ':' + at;
    const expiresIn = this.jwtConfig.expiresIn;
    this.cacheUtil.set(key, JSON.stringify(uc), 'EX', expiresIn);
    const vo = new LoginVO();
    vo.accessToken = at;
    vo.expiresIn = expiresIn;
    return vo;
  }

}

使用Postman驗(yàn)證

  • 調(diào)用接口(未設(shè)置憑證);


    未設(shè)置憑證
  • 使用登陸接口獲取token;


    獲取憑證
  • 調(diào)用接口(使用憑證);


    使用憑證

版權(quán)所有,轉(zhuǎn)載請注明出處 [碼道功成]

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容