Angular 4 jwt authentication

Viewed 1733

Authentication using passport jwt from angular app I am setting my request header in angular 4 as I am using passport jwt in server side but i am getting unauthorized error

`let strategy = new JwtStrategy(jwtOpts, (jwt_payload, cb)=>{
    let stmt = "select * from user where id = ?";
    let id = jwt_payload.id;
    connection.query(stmt, id, (error, result) => {
        if(error){
            throw error;
        }
        if(result){
            var userinfo = {
                email: result[0].email,
                id: result[0].id
            }
            cb(null, userinfo);
        }
        else{
            cb(null, false);
        }
    })
})`

//this is my route
`app.use('/tournament',passport.authenticate('jwt', {session: false}), tour_route);` 


//This is my angular call
 createTournament(name: string){
        this.token = 'JWT ' + this.authService.getToken();
        const body = {
            name
        }
        this.http.post('http://localhost:8000/tournament',
            {
                headers: new HttpHeaders().set('Authorization', this.token)
            })
            .subscribe(
                response => {}
                );
    }

But i am getting an unauthorised access even if i am sending the right token
2 Answers

Try adding Bearer or Token or Basic along with the Token, this should solve the issue.

headers: new HttpHeaders().set('Authorization', 'Bearer '+this.token)

In case of backend, you have to pass "username" and "password" fields in the form of post method. Because PassportJS package will expected only username and password as a request data.

Then using passport-jwt package, you can generate token and pass that token in the request data of login API. After that from frontend, whenever you will make any call to the backend. then you need to pass that token with Header details. you can access then token user req.headers option and verify the token jwt.verify. if it will verfied then call next() function. SO that it will call next middle ware. Other wise, It will send error mesage to frontend

Related