Nodejs Nestjs认证插件@nestjs/passport的使用
Nodejs Nestjs认证插件@nestjs/passport的使用[@nestjs](/user/nestjs)/passport
是一个用于在 NestJS 项目中集成 Passport.js 的库。Passport.js 是一个 Node.js 框架,用于处理身份验证。下面是如何在 NestJS 项目中使用 [@nestjs](/user/nestjs)/passport
进行基本认证的步骤。
1. 安装必要的依赖
首先,你需要安装 [@nestjs](/user/nestjs)/passport
, passport
, passport-http-bearer
(或任何你想要使用的策略)以及 @types/passport
:
npm install [@nestjs](/user/nestjs)/passport passport passport-http-bearer @types/passport
如果你还需要 JWT 认证,可以安装 [@nestjs](/user/nestjs)/jwt
和 jsonwebtoken
:
npm install [@nestjs](/user/nestjs)/jwt jsonwebtoken
2. 配置模块
在你的主应用模块(通常是 app.module.ts
)中导入 PassportModule
:
import { Module } from '[@nestjs](/user/nestjs)/common';
import { PassportModule } from '[@nestjs](/user/nestjs)/passport';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'bearer' }),
// 其他模块
],
// ...
})
export class AppModule {}
3. 创建认证策略
创建一个新的服务来定义你的认证策略。例如,创建一个 auth.strategy.ts
文件:
import { Injectable, UnauthorizedException } from '[@nestjs](/user/nestjs)/common';
import { PassportStrategy } from '[@nestjs](/user/nestjs)/passport';
import { Strategy } from 'passport-http-bearer';
@Injectable()
export class AuthStrategy extends PassportStrategy(Strategy) {
constructor() {
super();
}
async validate(token: string): Promise<any> {
// 在这里验证 token,例如从数据库或缓存中查找用户
if (token === 'your-expected-token') {
return { userId: 123 };
}
throw new UnauthorizedException();
}
}
4. 使用认证策略
在你的控制器中使用 @UseGuards(AuthGuard('auth'))
来保护路由:
import { Controller, Get, UseGuards } from '[@nestjs](/user/nestjs)/common';
import { AuthGuard } from '[@nestjs](/user/nestjs)/passport';
@Controller('users')
export class UsersController {
@Get()
@UseGuards(AuthGuard('auth'))
getUsers() {
return [{ id: 1, name: 'John Doe' }];
}
}
5. JWT 认证(可选)
如果你需要使用 JWT,可以创建一个 JWT 策略并配置它:
import { Injectable, UnauthorizedException } from '[@nestjs](/user/nestjs)/common';
import { PassportStrategy } from '[@nestjs](/user/nestjs)/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'your-secret-key',
});
}
async validate(payload: any) {
return { userId: payload.sub };
}
}
然后在你的控制器中使用这个策略:
@UseGuards(JwtAuthGuard)
以上就是使用 [@nestjs](/user/nestjs)/passport
进行基本认证的基本步骤。你可以根据自己的需求调整这些示例代码。
当然,没问题!想象一下,@nestjs/passport就像是给你的Node.js应用加上了一把超级智能的锁。首先,你需要安装它,就像给你的门装上这把锁一样(npm install [@nestjs](/user/nestjs)/passport passport
)。
接着,你需要配置它,就像是设定锁的密码。你得创建一个策略(strategy),比如JWT策略,来告诉系统如何验证用户(例如,通过用户名和密码)。
然后,你可以开始用它来保护你的API了,就像是用这把锁来保护你的秘密花园。你可以在控制器的方法上添加装饰器,比如@UseGuards(JwtAuthGuard)
,这样只有拥有正确“钥匙”的人才能进入。
最后,别忘了测试你的新锁是否好用,确保只有正确的人才能访问你的资源。这样,你就成功地为你的应用增加了认证功能,让安全性和便捷性并存!
在NestJS中,使用@nestjs/passport
模块可以非常方便地集成认证功能。下面我将简要介绍如何配置和使用这个模块来实现基于JWT(JSON Web Token)的认证。
1. 安装必要的依赖
首先,你需要安装一些必要的包:
npm install @nestjs/passport passport passport-jwt @nestjs/jwt
2. 配置Passport
接下来,在你的应用程序中配置Passport。通常,这会涉及到创建一个策略文件,例如auth.strategy.ts
。
// auth.strategy.ts
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET,
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
在这个例子中,我们定义了一个名为JwtStrategy
的策略,它从请求头中提取JWT,并验证其有效性。
3. 创建控制器处理认证逻辑
接下来,我们需要一个控制器来处理登录和获取token的逻辑。
// auth.controller.ts
import { Controller, Post, Body, HttpException, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service';
import { JwtService } from '@nestjs/jwt';
@Controller('auth')
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly jwtService: JwtService,
) {}
@Post('login')
async login(@Body() user: {username: string, password: string}) {
const payload = await this.authService.validateUser(user);
if (!payload) {
throw new HttpException('Invalid credentials', HttpStatus.UNAUTHORIZED);
}
return {
access_token: this.jwtService.sign(payload),
};
}
}
4. 实现服务逻辑
最后,我们需要实现服务逻辑来验证用户凭据。
// auth.service.ts
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
validateUser({ username, password }: { username: string; password: string }) {
// 这里应该包含实际的用户验证逻辑,比如查询数据库
// 为了演示,我们假设用户名是 "admin",密码是 "password"
if (username === 'admin' && password === 'password') {
return { username, sub: 1 };
}
return null;
}
}
5. 配置应用模块
别忘了在你的应用模块中导入所需的模块并注册它们。
// app.module.ts
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthModule } from './auth/auth.module';
import { AuthService } from './auth/auth.service';
import { AuthController } from './auth/auth.controller';
import { JwtStrategy } from './auth/strategies/jwt.strategy';
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '60m' },
}),
AuthModule,
],
providers: [AuthService, JwtStrategy],
})
export class AppModule {}
以上就是使用@nestjs/passport
模块的基本步骤。当然,实际应用中还需要考虑更多细节,如错误处理、日志记录等。希望这些示例代码能够帮助你快速上手。
@nestjs/passport
是一个用于NestJS框架的认证插件,它结合了Passport.js的功能。首先安装必要的依赖:
npm install @nestjs/passport passport passport-local
配置策略:
// auth.strategy.ts
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor() {
super();
}
async validate(username: string, password: string): Promise<any> {
// 在这里进行验证逻辑
const user = { id: 1, username: 'test', password: 'test' };
if (user && user.password === password) {
return user;
} else {
throw new UnauthorizedException();
}
}
}
在模块中注册策略并使用装饰器进行路由保护:
// app.module.ts
import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth.module';
import { APP_GUARD } from '@nestjs/core';
import {AuthGuard} from '@nestjs/passport';
@Module({
imports: [AuthModule],
providers: [
{
provide: APP_GUARD,
useClass: AuthGuard('local'),
},
],
})
export class ApplicationModule {}
在控制器中使用认证:
// auth.controller.ts
import { Controller, Post, Body, UseGuards } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LocalAuthGuard } from './local-auth.guard';
@Controller()
export class AuthController {
constructor(private authService: AuthService) {}
@UseGuards(LocalAuthGuard)
@Post('login')
async login(@Body() body) {
return this.authService.login(body.username, body.password);
}
}
这样,你就完成了基本的认证设置。