typescript - Mengapa pelayan berasaskan nestjs saya yang menggunakan Passport sentiasa mengembalikan 401 untuk endpoint saya, walaupun apabila Token JWT yang sah ada?
Anda tidak akan percaya ini, tetapi saya sedang membina API untuk pelayan Todo! Hooray!
Saya menggunakan Nestjs, Auth0, dan Passport untuk melakukan pengesahan saya. Saya telah mengesahkan bahawa klien menghantar token yang sah.
Saya juga sedang tarik rambut saya kerana nampaknya saya tidak dapat membuat pengawal /todo mengembalikan apa-apa selain ralat 401.
Saya telah melakukan penelitian saya di Google, tetapi malangnya, tiada apa yang nampaknya berkesan.
Jadi, ini adalah Strategi JWT saya:
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);
}
}
Berikut adalah pengawal todo saya:
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);
}
}
Jika anda berminat, tinjauan lengkap mengenai projek ini boleh didapati di sini:
https://github.com/NickHodges/nestjstodoserver
Panggilan ke http:/localhost:3000/todos akan mengembalikan 401 tidak kira apa yang saya cuba.
Ada idea daripada sesiapa?