Ways to verify the identity of a user using an external authentication service

One of my microservices deals with user login and registration. Upon making a request to localhost:8080 with the body

{ "username": "test", "password":"test"}
, I receive an authentication token like this:
{ "token":"asdfsadfasdf..." }
.

I need to utilize this token in another microservice to authenticate the user before sending a request to my endpoint. The code snippet for this scenario looks like:

import { Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
    @Get()
    @UseGuards(JwtAuthGuard)
    private async getHello(): Promise<void> {
        console.log("Hello world");
    }
@Module({
  imports: [
        JwtModule.register({
      secret: 'secretKey',
    }),
    JwtStrategy,
    PassportModule.register({ defaultStrategy: 'jwt' })
],
  providers: [AppService],
  controllers: [AppController]
})
export class AppModule{}

Upon launching my Get request, I encountered an error message:

[Nest] 10472   - 04.05.2021, 17:14:00   [ExceptionsHandler] Unknown authentication strategy "jwt" +3677ms
Error: Unknown authentication strategy "jwt"

Regarding the authentication strategy, the following block of code is used:


@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
    constructor() {
        super({
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
          secretOrKey: 'secret',
        });
    }
}

I'm seeking guidance on what went wrong with setting up my authentication strategy and why it might not be working correctly.

Thank you for any assistance!

Answer №1

Ensure that your JwtStrategy is relocated from the imports section to the providers array. Remember, providers should always be placed in the appropriate array and not within imports which are reserved for modules only.

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

Vue3 and Typescript issue: The property '$el' is not recognized on type 'void'. What is the correct way to access every existing tag type in the DOM?

Currently, I am in the process of migrating a Vue2 project to Vue3 and Typescript. While encountering several unusual errors, one particular issue with $el has me puzzled. I have been attempting to target every <g> tag within the provided template, ...

It appears that the Next.js environment variables are not defined

Upon setting up a fresh next.js project using npx create-next-app@latest and configuring some environment variables in the .env.local file, I encountered an error when attempting to run the server. "Failed to load env from .env.local TypeError: Cannot ...

Converting JSON information into a JavaScript array of objects

I have a JSON file containing placeholder articles for testing purposes. I'm using jQuery to parse the data from the JSON file and create an array of objects with the retrieved information. Take a look at my JSON file: { "news": [ { ...

Customizing data attributes for child components in Vue 2

In my Vue project, I have created a multi-page questionnaire using the v-show directive within a container called RiskAssessmentTest.vue. To handle loading questionnaire drafts, I have a component named RiskAssessmentDrafts.vue, which has the following st ...

Issues with the Winston transport for Loggly are causing inconsistent performance

I have implemented Winston with 3 transports: Console, File, and Loggly (using https://github.com/loggly/winston-loggly-bulk). While the Console and File transports are functioning properly, I am facing an issue with the Loggly transport. It only logs my ...

How to resolve the error of "Objects are not valid as a React child" in NextJs when encountering an object with keys {children}

I am currently working on a nextjs application and I have encountered an issue with the getStaticPaths function. Within the pages folder, there is a file named [slug].tsx which contains the following code: import { Image } from "react-datocms"; i ...

Deciphering a Base64 document from a JSON reply on the user's end: What's the process?

My project involves rendering a file on the server side, where I pass it as a "base64" string via json. I am now faced with the task of decoding and downloading this file on the client side. Below is a simplified version of the code that is relevant to my ...

Display the length of an array using AngularJS

Hey there, I'm currently having an issue with printing a list where each entry is supposed to follow the format "element X of TOTAL". However, instead of displaying the total value, it appears as blank text. It seems like a simple mistake, but for som ...

The code functions correctly on JSfiddle, however it is not executing properly on my website

When I tried to implement the code from this jsfiddle link: http://jsfiddle.net/mppcb/1/ on my website (), it didn't work as expected: Here is the HTML code snippet: <form id="myform" novalidate="novalidate"> <input type="text" name="fi ...

how to adjust the width of table columns dynamically using ng-repeat and AngularJS

Working on a user interface that contains a table where the column widths adjust according to percentage data. I'm using ng-repeat to populate the table, but need help setting unique widths for each piece of data received. Here's some of my Angul ...

Internet Explorer 11 Ajax problem

Once again, Internet Explorer is causing some issues. I have a file called validation.php where the values from a text box are sent for validation. The text box value is read and then a result indicates whether it is valid or not. This functionality work ...

Unable to display script in the sources tab on NW.js 16

After updating to the latest version of NW.js (nwjs-sdk-v0.16.1-linux-x64) and attempting to migrate my project over, I encountered a strange issue with debugging. The script I was working on, named "bunny.js", would show up under "Applications" but not in ...

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

What is the best approach to creating an array within my formgroup and adding data to it?

I have a function in my ngOnInit that creates a formgroup: ngOnInit() { //When the component starts, create the form group this.variacaoForm = this.fb.group({ variacoes: this.fb.array([this.createFormGroup()]) }); createFormGroup() ...

Can TypeScript Implement a Dictionary Feature Similar to C#?

Looking for guidance on how to use TypeScript interface to define these C# models: public class PageModel { public long Id { get; set; } public string Name { get; set; } public IDictionary<string, FieldModel> Fields { get; set; } } pu ...

Issues with the functionality of minimized AngularJS JavaScript files

I combined all JS files into one and minified them, but now none of the site features are working. There were too many separate JS files to include individually, so I decided to merge them together. Is there a better method to reduce the number of HTTP r ...

Turning HTML into an image with the power of JavaScript

Utilizing html2canvas to convert a div into an image, everything is functioning properly except for the Google font effect. The image shows how it eliminates the effect from the text. https://i.stack.imgur.com/k0Ln9.png Here is the code that I am using f ...

The specified property 'slug' is not found within the designated type 'ParsedUrlQuery | undefined'

I am faced with an issue in my code where I am attempting to retrieve the path of my page within the getServerSideProps function. However, I have encountered a problem as the type of params is currently an object. How can I convert this object into a stri ...

Filtering text for highlighting in Vue.js is a breeze

Struggling to create a text highlight filter using vuejs. The task involves iterating through an array of words, highlighting any matches with a span and class. However, I'm facing difficulty in getting the data to return with proper HTML formatting i ...

What is the most effective approach for addressing errors in both the server and client sides while utilizing nodejs and express?

Seeking the most effective approach for handling errors in a response - request scenario. Here is an example of a route that receives a request: app.get('/getInfo', function (req, res, next) { let obj = {} try { obj = { ...