Shamnad P S
Shamnad P S

Reputation: 1173

Authentication failure while using nestjs authentication

I am trying to implement authentication using nestjs documentation. https://docs.nestjs.com/techniques/authentication

And I am implementing JWT Authentication and when trying to access an API which is being authenticated, I am getting validation error, even before validating. Has anyone faced similar issue.

@Get()
  @UseGuards(AuthGuard('jwt'))
  async findAll(): Promise<UserDto[]> {
    return this.userService.findAll();
  }

This route is giving me UnAuthorized error. I am really new to Typescript and nestjs

My code is available here in my GitHub repo. Please let me know what went wrong. https://github.com/shamnadps/TypeScript_Project/blob/master/src/user/user.controller.ts#L23

Upvotes: 0

Views: 2373

Answers (2)

A. Maitre
A. Maitre

Reputation: 3599

Your - slight but critical - error resides in the secretOrKey value you're using to sign your token. You have different values between src/auth/jwt.strategy.ts and src/auth/auth.service.ts.

In src/auth/auth.service.ts:
Instead of this:

async createToken() {
    const user: UserDto = { name: 'shamnad', phoneNumber: '12435' };
    return jwt.sign(user, 'secretkey'); // <== /!\ focus on this one /!\
}

Use this:

async createToken() {
        const user: UserDto = { name: 'shamnad', phoneNumber: '12435' };
        return jwt.sign(user, 'secretKey'); // <== /!\ focus on this one /!\
}

Because you use secretKey to sign your token, and not secretkey (notice the camel case):

constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secretKey', // <== /!\ focus on this line /!\
    });
}

To avoid such problems, I'd recommend you to use process.env.<your-variable> instead of directly setting config manually in strings.


It would look something like this in src/auth/jwt.strategy.ts:

constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: process.env.SECRET
    });
}

and in src/auth/auth.service.ts, like this:

async createToken() {
    const user: UserDto = { name: 'shamnad', phoneNumber: '12435' };
    return jwt.sign(user, process.env.SECRET); // <== /!\ focus on this one /!\
}

Finally, to set the environment variable, execute the following command based on your OS:
- Mac OS: export SECRET=<your-secret-key>
- Windows: set SECRET=<your-secret-key>


I hope it helps ;)

Upvotes: 2

small white
small white

Reputation: 469

how did you access the route?

you must create the token first.

don't know if this gives you a hint

enter image description here

Upvotes: 0

Related Questions