Angular authentication 4 jwt

Authenticate using jwt passport from angular app I am setting request header in angular 4 as I am using server side jwt passport 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

      

+3


source to share


2 answers


Try adding Bearer or Token or Basic along with Token, that should fix the problem.



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

+2


source


In the case of the backend, you must pass the username and password fields in the form of a mail method. As the PassportJS package will only expect username and password as request data.



Then, using the passport-jwt package , you can generate a token and pass that token in the login API request data. After that, from the outside interface, whenever you call the server. then you need to pass this token with header details. you can access the user's req.headers parameter of the user and check the jwt.verify token. if it gets checked, call next () function . SO that it will trigger the next medium cookware. Another wise, it will send a mesage error for the interface

0


source







All Articles