'missing credentials in NestJs Passport
I've built an NestJS API with authentification. I'm using NestJS passport and I create a JSON web token when a user logs in. I've done numerous searches and I really don't know what I'm doing wrong. I get the error
missing credentials from the API console.
Does anyone has a solution for this issue?
Here is my authentification service:
import { Injectable } from '@nestjs/common';
import { UtilisateurService } from '../utilisateur/utilisateur.service';
import { JwtService } from '@nestjs/jwt';
const bcrypt = require('bcryptjs');
import { jwtConstants } from './constants';
@Injectable()
export class AuthService {
constructor(private utilisateurService : UtilisateurService, private jwtService: JwtService) {}
async validateUser(username: string, pass: string): Promise<any> {
const user = await this.utilisateurService.findOne(username);
if (user && bcrypt.compareSync(pass, user.password)) {
const { password, ...result } = user;
return result;
}
return null;
}
async login(user: any) {
// const payload = { username: user.username, sub: user.userId };
const payload = { username: user.username, sub: user._id };
return {
access_token: this.jwtService.sign(payload),
};
}
}
I sent the request like this:
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IlV0aWxpc2F0ZXVyMSIsInN1YiI6IjYxZjIyZjQzYTBjMWE5M2YxYTVkNDE1MCIsImlhdCI6MTY0NDIxMjM4NSwiZXhwIjoxNjQ0MjE1OTg1fQ.CDItoaUwhrCUs7XAb9vpvfikq8yX7E89nj_luU576MU'
export const config = {
headers: {
Authorization : 'Bearer ' + token
}
}
mounted() {
// console.log(VueCookies.get("user-params").access_token)
axios.get('http://localhost:3000/projet', config)
.then(response => {
this.projets = response.data
// console.log(this.projets)
this.projetsSearched = this.projets
})
.catch(e => {
console.log(e)
})
},
And here is my local strategy
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, 'thejwt') {
constructor(private authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any>{
const user = await this.authService.validateUser(username,password);
const user2 = user._doc;
if(!user2){
throw new UnauthorizedException();
}
return user2;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|