While trying to access my login route in the app.controller.ts of my rest api built with Nestjs and Prisma, I encountered a 401 error response. I have been closely following the official documentation provided by Nestjs on authentication (https://docs.nestjs.com/security/authentication).
Below is the snippet from ./app.controller.ts :
import { LocalAuthGuard } from './auth/local-auth.guards';
@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
private readonly authService: AuthService,
) {}
@UseGuards(LocalAuthGuard)
@Post('auth/login')
async login(@Request() req) {
return req.user;
}
The contents of ./auth/local.strategy.ts are as follows:
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validateUser(username, password);
console.log('validation');
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
And finally, here's the content of ./auth/local-auth.guards.ts:
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}
Based on my understanding, the use of @UseGuards(LocalAuthGuard)
should grant access to the /auth/login
function only if the
validate(username: string, password: string)
method does not throw an error. However, it seems that this validation process is never executed, leading to the persistent 401 error that I'm unable to pinpoint (hence this post).
Thank you for taking the time to read this, any assistance offered will be greatly appreciated.