我是身份验证的新手。
我正在使用nodeJS开发一个应用程序,该应用程序使用nestJS后端以及Passport和JWT策略的身份验证机制。
这是我在github的某个仓库中找到的登录控制器。 我已经实现了它并且可以工作。我可以进行ajax调用,进行身份验证并获得令牌作为响应。
auth.controller.ts:
import { Controller, Post, HttpStatus, HttpCode, Get, Response, Body, Param, Req, Res } from '@nestjs/common';
import { AuthService } from './auth.service';
import { UserService } from '../user/user.service';
import { User } from 'user/user.entity';
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService,
private readonly userService: UserService) {}
@Post('login')
async loginUser(@Response() res: any, @Body() body: User) {
if (!(body && body.email && body.password)) {
return res.status(HttpStatus.FORBIDDEN).json({ message: 'Email and password are required!' });
}
const user = await this.userService.findOneByEmail(body.email);
if (user) {
if (await this.userService.compareHash(body.password, user.password)) {
return res.status(HttpStatus.OK).json(await this.authService.createToken(user.email));
}
}
return res.status(HttpStatus.FORBIDDEN).json({ message: 'Email or password wrong!' });
}
}
我试图理解为什么我应该将令牌返还给客户? 我应该在哪里保存令牌以及如何读取令牌? 我知道Passport.js是应该处理所有这些问题的中间件,但是我不知道如何。
起初,我以为应该将其保存为httpOnly cookie,但现在我确定是否有必要,或者护照正在为我做类似的事情。
还有更多代码:
auth.module.ts
import { Module, MiddlewareConsumer, forwardRef } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import { UserModule } from '../user/user.module';
import { PassportModule } from '@nestjs/passport';
import { AuthController } from '../auth/auth.controller';
import { PatientModule } from '../patient/patient.module'
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: 'secretKey',
signOptions: {
expiresIn: 3600,
},
}),
UserModule,
PatientModule
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
auth.service.ts
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from './jwt-payload.interface';
import { UserService } from '../user/user.service';
@Injectable()
export class AuthService {
constructor(private readonly jwtService: JwtService, private readonly userService: UserService,) {}
async createToken(email) {
const expiresIn = 3600
const user: JwtPayload = { email:email};
const token = await this.jwtService.sign(user);
return {
token,
expiresIn: expiresIn
};
}
async validateUser(payload: JwtPayload): Promise<any> {
return await this.userService.findOneByEmail(payload.email);
}
}
jwt.strategy.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from './auth.service';
import { JwtPayload } from './jwt-payload.interface';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
});
}
async validate(payload: JwtPayload): Promise<boolean> {
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
也许这个问题会被认为是一个不好的问题,但是我是一个真正的新手,我尝试阅读Stack Trace和Passport.js documentation,但一无所获。