nestjs 配置Authorization
时间: 2024-01-02 19:04:47 浏览: 24
在 NestJS 中配置 Authorization 可以通过使用 Passport 模块实现。Passport 是一个 Node.js 的身份验证中间件,可以支持多种策略,如 JWT、OAuth 等。
以下是一个简单的配置步骤:
1. 安装 Passport 和相关策略
```
npm install --save @nestjs/passport passport passport-jwt
```
2. 创建一个 AuthModule 并导入 PassportModule
```typescript
// auth.module.ts
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
@Module({
imports: [PassportModule],
})
export class AuthModule {}
```
3. 创建一个 JwtStrategy 类
```typescript
// jwt.strategy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
```
4. 在 AuthModule 中导入 JwtStrategy
```typescript
// auth.module.ts
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [PassportModule],
providers: [JwtStrategy],
})
export class AuthModule {}
```
5. 在需要进行身份验证的地方使用 @UseGuards(AuthGuard('jwt')) 装饰器
```typescript
// protected-route.controller.ts
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller('protected')
export class ProtectedRouteController {
@UseGuards(AuthGuard('jwt'))
@Get()
protectedRoute() {
return 'This route is protected';
}
}
```
以上是一个简单的配置过程,你需要自行根据你的需求进行具体的配置。其中,JwtStrategy 是用来验证 JWT 的策略,可以根据具体需求进行更改。在 validate 方法中,你可以获取 JWT 的 payload,并返回一个包含用户信息的对象。在需要进行身份验证的地方,可以使用 @UseGuards(AuthGuard('jwt')) 装饰器来进行保护。