iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 11
0
Modern Web

讀官網文件邊走邊學nest.js系列 第 11

Day11-Guard(Authentication) in nest.js(上)

驗證(authentication)部分在nest.js也是跟AngularGuard這一套來使用,authentication邏輯需要另外建立class並實作CanActivate介面

CanActivate僅需實作canActivate方法回傳:

  • true 允許client存取資源
  • false 丟出UnauthizedException

假設來源是localhost才權限新增使用者

建立auth.guard.ts

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate { // 實作CanActive介面
  canActivate(
    context: ExecutionContext, // 可以取得對應controller及request/request資訊
  ): boolean | Promise<boolean> | Observable<boolean>  { //回傳boolean型別,支援非同步
    // 驗證邏輯
    const req=context.getRequest(); // 取得request物件
    const ctrl=context.getClass(); // nest.js利用reflect metadata取得Controller name
    Logger.log(`Controller Name: ${ctrl.name}`);
    const handler=context.getHandler(); // nest.js利用reflect metadata取得存取資源對應的方法
    Logger.log(`Method Name: ${handler.name}`);
    if(req.hostname === 'localhost'){
        Logger.log(`Requested From: ${req.hostname}`);
        return true;
    }
    return false;
  }
}

用@UseGuards註冊AuthGuard

app.controller.ts

@Controller()
@UseGuards(AuthGuard)
@UseFilters(HttpInterceptorException)
export class AppController {
  ...
  @Post()
  @UsePipes(UserDTOValidationPipe)
  create(@Body() userDTO: UserDTO){
    return `使用者:${userDTO.username}已建立`;
  }
  ...
}

使用postman測試

console output

前面的例子用主機/IP來決定存取權限,比較少見
通常使用role/group來管理使用者權限

這部份明天繼續


上一篇
Day10-Exception in nest.js(下)
下一篇
Day12-Guard in nest.js(下)
系列文
讀官網文件邊走邊學nest.js31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言