NestJs JWT Authentication返回401

问题描述 投票:0回答:3

我在nestJs中实现了jwt身份验证。但是,每当我尝试使用以下授权标头进行身份验证时:

Bearer <token> or JWT <token>

我得到401.这些是我的身份验证文件

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: `${process.env.SECRET}`,
    });
  }

  async validate(payload: Credentials) {
    const user: Account = await this.authService.validateAccount(payload);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}


@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  canActivate(context: ExecutionContext) {
    return super.canActivate(context);
  }

  handleRequest(err, user, info) {
    if (err || !user) {
      throw err || new UnauthorizedException();
    }
    return user;
  }
}

这是我的auth模块

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secretOrPrivateKey: `${process.env.SECRET}`,
    }),
    AccountModule,
  ],
  providers: [AuthService, JwtStrategy],
  controllers: [AuthController],
  exports: [PassportModule, AuthService],
})
export class AuthModule {

}
javascript node.js jwt passport.js nestjs
3个回答
0
投票

只有在传递有效的jwt令牌时才会调用validate。当令牌使用不同的秘密签名或过期时,将永远不会调用validate。确保您拥有有效的令牌。您可以使用jwt debugger检查您的令牌。


0
投票

我遇到了同样的问题。这里我的代码(工作)供你比较:

SRC / AUTH / auth.module.ts

import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import { UserModule } from 'src/user/user.module';
import { PassportModule } from '@nestjs/passport';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: '1d',
      },
    }),
    UserModule,
  ],
  providers: [AuthService, JwtStrategy],
  exports: [PassportModule, AuthService],
})
export class AuthModule {}

SRC / AUTH / auth.service.ts

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from './interfaces/jwt-payload.interface';
import { UserService } from 'src/user/user.service';

@Injectable()
export class AuthService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly userService: UserService,
  ) {}

  makeToken(payload: JwtPayload) {
    const { email } = payload;
    return this.jwtService.sign({ email });
  }

  checkToken(token: string) {
    return this.jwtService.verify(token);
  }

  async validateUser(payload: JwtPayload) {
    return await this.userService.read(payload.email);
  }
}

SRC / AUTH / jwt.strategy.ts

import { Strategy, ExtractJwt, VerifiedCallback } from 'passport-jwt';
import { AuthService } from './auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtPayload } from './interfaces/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, done: VerifiedCallback) {
    const user = await this.authService.validateUser(payload);
    if (!user) {
      done(new UnauthorizedException(), false);
    }
    return done(null, user);
  }
}

SRC / AUTH /接口/ JWT-payload.interface.ts

export interface JwtPayload {
  email: string;
}

SRC /帐号/ account.module.ts

import { Module } from '@nestjs/common';
import { AccountController } from './account.controller';
import { PassportModule } from '@nestjs/passport';
import { AuthModule } from 'src/auth/auth.module';

@Module({
  imports: [AuthModule],
  controllers: [AccountController],
})
export class AccountModule {}

SRC /帐号/ account.controller.ts

import { Controller, UseGuards, Post } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('account')
export class AccountController {
  @Post('skills')
  @UseGuards(AuthGuard())
  updateSkills() {
    return console.log('something');
  }
}

P.S。:我没有做JwtAuthGuard。

我希望它能帮助你:)


0
投票

您可以查看护照和NestJS的最低工作示例

https://github.com/leosuncin/nest-auth-example

与您的代码的主要区别:

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }), // I don't do this because I explicity call every stratategy
    JwtModule.register({
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: '1d',
      },
    }),
    UserModule,
  ],
  providers: [AuthService, JwtStrategy],
  exports: [PassportModule, AuthService], // I don't do this
})

我不使用任何JwtAuthGuard只使用默认值。

© www.soinside.com 2019 - 2024. All rights reserved.