The inability to access a route with an authentication guard in the app controller is causing the validate function in the local strategy file to not run

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.

Answer №1

Most of the time, the reason for this error is that you are not making a POST request with body parameters for username and password. If you wish to use something different like email, then you should provide the object { usernameField: 'email' } when calling super() in the constructor() of your LocalStrategy. If this does not solve the issue, please provide more information about what your request entails.

To gain further insight into the error, consider including this code snippet in your LocalAuthGuard:

handleRequest(...args: Parameters<InstanceType<ReturnType<typeof AuthGuard>>['handleRequest']> {
  console.log(args);
  return super.handleRequest(...args);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to connect to a library using a script within a Typescript React application?

I'm a newbie to React and haven't worked on web development in years, so I'm facing a basic issue: Currently, I'm working on implementing a Stripe-based payment flow in a React web app (written in Typescript) and I've hit a roadbl ...

Creating a dynamic multidimensional array or object in AngularJS: tips and tricks

Below is the code snippet where I am attempting to dynamically construct an associative array in angularJs: $scope.details = {"profilesFound": [ "https: //twitter.com/alexandreagular", "https: //twitter.com/?profile_id=46130006", "https: //f ...

I'm having trouble figuring out how to access response headers with HttpClient in Angular 5. Can anyone

I recently developed an authentication service in Angular 5, where I utilize the HttpClient class to make a POST request to my backend server. The backend server then responds with a JWT bearer token. Here is a snippet of how my request looks: return thi ...

What steps should I take to resolve the issue with running npm start?

I am encountering an issue while using React and trying to run my application. When I execute "npm run start," I receive the following error message: npm ERR! Missing script: "start" npm ERR! npm ERR! Did you mean one of these? npm ERR! npm star # Mark ...

Numerous applications of a singular shop within a single webpage

I have a store that uses a fetch function to retrieve graph data from my server using the asyncAction method provided by mobx-utils. The code for the store looks like this: class GraphStore { @observable public loading: boolean; @observable ...

The current version of HTML5 Context Menus is now available

I'm in need of implementing the HTML5 Context Menu feature. Currently, only Firefox supports it. My main objective is to add some menu options without replacing the existing context menu. How can I achieve the same functionality now? I am aware of va ...

The desired result is not appearing when using a `fetch` request, but it does show up with an

I am facing an issue with two different requests - one using ajax and the other using fetch, its successor. When I send my data using fetch to the same API as ajax, I notice that the results are not consistent. Ajax $.post(this.config.baseUrl + this ...

The JSON ticker for BTC/LTC has stopped functioning

I've been relying on this JSON ticker for the past month and it's been smooth sailing. However, today it suddenly stopped working. Any ideas on what might have caused this issue? $(function () { startRefresh(); }); function startRefresh() { ...

Express js is unable to retrieve the page at /page

I'm facing a persistent routing error on express.js. Despite multiple attempts to fix it by referring to the documentation and making changes, I'm still stuck. Here's the basic content of the link pointing to the '/sell' route: i ...

Suggestions for improving string.replace across various attributes

I have been working on an application with an editable script feature. As I go through the script, I find myself needing to replace placeholders with local data. While this process is functional, it feels quite messy. initScript(script: LegalScript, lead: ...

Using React to Render a Component with Local Storage Information

I'm in the process of developing a history list component for a form within a react application and encountering difficulties with local storage. The goal is to display a list of previous user inputs from the local storage data. My current approach i ...

What is the best way to disable list items in a UI?

Check out my assortment: <ul class="documents"> <li class="list_title"><div class="Srequired">NEW</div></li> <li class="doc_price>1</li> <li class="doc_price>2</li> <li c ...

What could be the reason for a jQuery script failing to execute when included in a PHP include statement from a different PHP page?

I'm currently working with javascript and php to manage cookies across different pages. On one page, I have a script that sets a value in a cookie variable and I want to retrieve that value on another page. Let's say the first page is named page1 ...

The value remains unchanged when using Renderer2.setProperty()

I am attempting to update the value using the rendered.setproperty() method, where the value is updating the second time on a listen event These are the values that I am sending for the first time as blank in some widget <ols-giftcard-payment-widget ...

How can I verify if an SVG file has a reliable source? (having troubles converting SVG to canvas)

While attempting to use an SVG generated by a chart plugin (https://wordpress.org/plugins/visualizer/), I am facing issues retrieving the source of the SVG-image being created. Interestingly, when using other SVGs with the same code, everything works perfe ...

In a React app, there are instances where `localstorage.getitem('key')` may result in returning null

I've encountered a strange issue while building a login form that sets a JWT token in localstorage. The problem arises when, despite being able to see the token in my console.log, setting localstorage.getitem('idToken') sometimes returns nul ...

Value as a String inside an Object

I am encountering an issue with using the obj to store string values in my project. The strings contain commas, and for some reason, it is not working as expected. const resizedUrl ={ 'mobile': "'images','400x/images' ...

The `sonarqube-scanner@^4.0.0` does not produce a non-zero exit code when a Quality Gate failure occurs

Latest SonarQube: Developer Edition v10.5.1 (90531) Sonarqube-scanner version: 4.0.0 or 4.0.1 Utilized npm package: https://www.npmjs.com/package/sonarqube-scanner Node.js version: 20.14 Upon executing the following command: npx sonarqube-scanner@^4.0.0 - ...

If the form is empty, clicking on the Login button will direct you to the page. It is necessary for an error to occur

What should happen when the form is empty and the Login button is pressed? Currently, the page opens without any errors. However, I want to display an error message under such circumstances. How can I modify the function to achieve this? const login = (e ...

Importing Laravel select2 library is necessary for enhancing user experience and improving

I've been attempting to incorporate select2 into my project without success. Every time I try these two methods, I always receive an error saying $('#state').select2 is not a function. However, when I include select2 in a standard <scrip ...