nestjs 登录注册接口
时间: 2023-07-08 19:26:37 浏览: 48
首先,你需要安装 `@nestjs/passport` 和 `passport-local` 两个依赖包,它们提供了 NestJS 中实现身份验证和授权的相关功能。
接着,你需要创建一个 `AuthModule` 模块,用来处理登录和注册的请求。在该模块中,你需要创建一个 `AuthService` 服务,用于处理用户的认证和授权操作,例如注册新用户、验证用户身份、生成 JWT 等。下面是一个简单的 `AuthService` 服务示例:
```typescript
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from './user.service';
@Injectable()
export class AuthService {
constructor(
private readonly userService: UserService,
private readonly jwtService: JwtService,
) {}
async validateUser(username: string, password: string): Promise<any> {
const user = await this.userService.findByUsername(username);
if (user && user.password === password) {
const { password, ...result } = user;
return result;
}
return null;
}
async login(user: any): Promise<any> {
const payload = { username: user.username, sub: user.userId };
return {
access_token: this.jwtService.sign(payload),
};
}
}
```
上述代码中,`validateUser` 方法用于验证用户的身份,如果验证通过,则返回用户的信息。`login` 方法用于生成 JWT,并将其包含在响应中返回给客户端。
接着,你需要在 `AuthModule` 模块中创建一个 `AuthController` 控制器,用于处理登录和注册的请求。下面是一个简单的 `AuthController` 控制器示例:
```typescript
import { Controller, Post, UseGuards, Request } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@UseGuards(AuthGuard('local'))
@Post('login')
async login(@Request() req) {
return this.authService.login(req.user);
}
@Post('register')
async register(@Request() req) {
// TODO: 实现用户注册逻辑
}
}
```
上述代码中,`@UseGuards(AuthGuard('local'))` 表示使用 `passport-local` 策略来验证用户的登录信息。`login` 方法用于处理登录请求,`register` 方法用于处理注册请求。
最后,你需要在 `AppModule` 中引入 `AuthModule` 模块,并将其添加到模块的 `imports` 中,以便 NestJS 可以自动加载该模块。
这就是一个简单的 NestJS 登录注册接口的实现方法。当然,具体实现还需要按照你的业务需求进行调整。