웹사이트 검색

typescript - 내 nestjs 기반 서버가 Passport를 사용함에도 불구하고 유효한 JWT 토큰이 있어도 내 엔드포인트에서 항상 401을 반환하는 이유는 무엇인가요?


너는 믿지 못할 거야, 하지만 나는 Todo 서버용 API를 만들고 있어! 야!

저는 인증을 위해 Nestjs, Auth0, 그리고 Passport를 사용하고 있습니다. 클라이언트가 유효한 토큰을 보내고 있는 것을 확인했습니다.

저도 /todo 컨트롤러가 401 오류 외에는 아무것도 반환하지 않아서 정말 답답합니다.

구글에 대해 철저히 조사를 했지만, 아쉽게도 아무 것도 효과가 없는 것 같습니다.

자, 제 JWT 전략은 다음과 같습니다:

import { passportJwtSecret } from 'jwks-rsa';
import { ExtractJwt, Strategy, VerifiedCallback } from 'passport-jwt';

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor() {
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
      }),

      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      //jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('jwt'),
      audience: 'http://localhost:3000',
      issuer: `https://${process.env.AUTH0_DOMAIN}/`,
    });
  }

  validate(payload: any, done: VerifiedCallback) {
    if (!payload) {
      console.log('DENIED!!!!!');
      done(new UnauthorizedException(), false); // 2
    }

    return done(null, payload);
  }
}

여기에 제 할 일 컨트롤러가 있습니다:

import { ValidationPipe } from './../utils/validation.pipe';
import {
  Controller,
  Get,
  Param,
  Body,
  Post,
  Put,
  Delete,
  Query,
  ParseBoolPipe,
  UsePipes,
  UseGuards,
} from '@nestjs/common';
import { ToDosService } from './to-dos.service';
import { classToPlain } from 'class-transformer';
import { Todo } from '../models/todo.model';
import { ObjectID } from 'typeorm';
import { AuthGuard } from '@nestjs/passport';

@Controller('todos')
@UseGuards(AuthGuard('jwt'))  
export class ToDosController {
  constructor(private todosService: ToDosService) {}

  @Get()
  async getAllTodos() {
    const todosEntities = await this.todosService.getAllTodos();
    const todos = classToPlain(todosEntities);
    return todos;
  }

  @Get('complete')
  async getTodos(@Query('iscomplete', new ParseBoolPipe()) isComplete) {
    let todosEntities: Todo[];

    if (isComplete) {
      todosEntities = await this.todosService.getCompletedTodos();
    } else {
      todosEntities = await this.todosService.getIncompleteTodos();
    }
    const todos = classToPlain(todosEntities);
    return todos;
  }

  @Get(':id')
  async getTodo(@Param('id') id: ObjectID): Promise<Todo> {
    return this.todosService.getTodo(id);
  }

  @UsePipes(new ValidationPipe())
  @Post()
  async createTodo(@Body() todo: Todo) {
    return this.todosService.createTodo(todo);
  }

  @Put(':id')
  async updTodo(@Param('id') id: ObjectID, @Body() todo: Todo) {
    return this.todosService.updateTodo(id, todo);
  }

  @Delete(':id')
  async deleteTodo(@Param('id') id: ObjectID) {
    return this.todosService.deleteTodo(id);
  }
}

원하신다면, 프로젝트에 대한 전체적인 내용은 여기에서 확인할 수 있습니다:

https://github.com/NickHodges/nestjstodoserver

어떤 시도를 하든 http:/localhost:3000/todos에 대한 호출은 401을 반환합니다.

누구에게서든 아이디어 있나요?