nest g guard auth
// src/guard/auth.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
// 在这里可以写一些你要的代码 TODO
return true; // 注意这里 true 和 false
}
}
1 ) 下面我们在 admin模块的 user 控制器中使用守卫
import { Controller, Get, UseGuards } from '@nestjs/common';
import { UserService } from '../../service/user/user.service'
import { AppService } from 'src/app.service';
import { BaseService } from 'src/module/common/service/base/base.service';
import { AuthGuard } from 'src/guard/auth.guard';
@Controller('admin/user')
// @UseGuards(AuthGuard) // 在这里写说明整个控制器会被控制
export class UserController {
constructor(
private userService:UserService,
private appService:AppService,
private baseService:BaseService,
) {}
@Get()
index() {
const list = this.userService.getUser()
console.log('list', list)
console.log(this.appService.getHello())
console.log(this.baseService.getList())
return '我是admin模块里的user控制器';
}
@Get('add')
add() {
return '我是admin模块里的user/add控制器';
}
@Get('edit')
@UseGuards(AuthGuard) // 在这里写只会控制这个方法、
edit() {
return '我是admin模块里的user/edit控制器';
}
}
2 ) 全局使用守卫
在根模块中配置
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
@Module({
providers: [
{
provide: APP_GUARD,
useClass: RolesGuard,
},
],
})
export class AppModule {}
在main.ts中配置
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AuthGuard } from 'src/guard/auth.guard';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalGuards(new AuthGuard()) // 全局守卫配置
await app.listen(3000);
}
bootstrap();
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const req = context.switchToHttp().getRequest() // 这个就相当于中间件中的request
console.log(req)
// TODO 你想要做的事情
return true;
}
}