Home > Software engineering >  Axios JWT in Vue JS
Axios JWT in Vue JS

Time:02-04

I'm trying to build an app that gets data from my API (Nest.js using Passport for authentification). I'm trying to give Axios the JWT created from the login request (which works perfectly fine), and I keep getting a 401 error.

It works fine when I test these requests with Postman. Here's my front-end code:

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2NDM3OTg4NTEsImV4cCI6MTY0MzgwMjQ1MX0.dpnzkM9Jvgp3fIG8s9avXIjBw3a_1c9GNmUqbAYyRQw'

export const config = {
    headers: {
        Authorization : 'Bearer '   token
    }
} 
export default {
    data() {
        return {
            projets: []
        }
    },
    mounted() {
        axios.get('http://localhost:3000/projet', config)
        .then(response => {
          this.projets = response.data
        })
        .catch(e => {
          console.log(e)
        })
    },
}

(The token is written in the code for the sake of testing.)

CodePudding user response:

Most of the time when you're getting a 401 with a JWT, the JWT either is expired, or has an invalid signature. To get more info on the JWT's problem, you can use a debugger like jwt.io, or you can add some extra logs into your guard

@Injectable()
export class JwtGuard extends AuthGuard('jwt') {
  handleRequest(err, user, info, context, status) {
    console.log({
      err,
      info,
      user,
      context,
      status,
    })
    return super.handleRequest(err, user, info, context, status)
  }
}

CodePudding user response:

It turns out my JWT hasn't a valid signature (I don't know why since i use JWTService.sign) However, after signing it correctly from jwt.io, i still have a 401 error... I don't know what to do

  •  Tags:  
  • Related