nestjs让jwt同时支持cookie模式

in nestjsnodejs with 3 comments

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);
}
Comments are closed.