nestjs中jwt.strategy.ts:
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
// import { jwtConstants } from './constants'
import { Request } from 'express';
import { UsersService } from '../users/service'
import { ConfigService } from '@nestjs/config';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly userService: UsersService,
private readonly configService: ConfigService
) {
super({
// jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
jwtFromRequest: ExtractJwt.fromExtractors([(request: Request) => {
const token = request.headers['authorization'] //正常使用headers的authorization jwt认证, 格式为:"Bearer jwt-key"
const stoken = request.cookies[this.configService.get('COOKIE_NAME')] //使用jwt封装到cookie中,使用cookie认证
return token?(token.split(' ')[1]):stoken
}]),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET,
});
}
async validate(payload: any) {
// 验证jwt是否正确
const user = await this.userService.get(payload.sub)
return user;
}
}
使用jwt来设置cookie:
service:
public getCookieWithJwtToken(user: any) {
const payload = { username: user.username, sub: user.id };
const token = this.jwtService.sign(payload);
// console.log(this.configService.get('JWT_EXPIRATION_TIME'), new Date())
return `${this.configService.get('COOKIE_NAME')}=${token}; HttpOnly; Path=/; Max-Age=${this.configService.get('JWT_EXPIRATION_TIME')}`;
}
controller:
@HttpCode(200)
@UseGuards(LocalAuthGuard)
@Post('login')
async logIn(@Req() request: RequestWithUser, @Res() response: Response, @Body() loginData: LoginDto) {
const cookie = this.authenticationService.getCookieWithJwtToken(request.user);
response.setHeader('Set-Cookie', cookie);
request.user.password = undefined;
return response.send(request.user);
}
本文由 admin 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Jan 15, 2021 at 06:02 pm