Shawn
Shawn

Reputation: 5260

jwt server side authentication JsonWebTokenError

I am trying to do some server side authentication.

In server side login()

var jwt = require('jsonwebtoken');
....
if (user.hash != hash(pass, user.salt)) {
    return invalid("Wrong password");
}

var token = jwt.sign(user, 'superSecret');

res.json({
      success: true,
      message: '',
      auth_token: token
});

In client side http

  createHero(hero: Hero) {
      let body = JSON.stringify({ hero });
      let headers = new Headers({ 'Content-Type': 'application/json' });
      let authToken = localStorage.getItem('auth_token');
      headers.append('Authorization', `Bearer ${authToken}`);
      let options = new RequestOptions({ headers: headers });    

      this.http.post(`${this._baseUrl}create/`, body, options)
               .map(response => response.json())
               .subscribe(data => {
                                    this._dataStore.heroes.push(data);   
                                    this._dataStore.hero = data;
                                    this._heroObserver.next(this._dataStore.hero);
                                  }, 
                          error => this.handleError('Could not create hero.')
                         );
  }

In server side validation

  var token = req.headers.authorization;
  var h = req.headers;

  // decode token
  if (token) {

    // verifies secret and checks exp
    aaa = jwt.verify(token, 'superSecret', function(err, decoded) {  
        console.log(decoded);    
      if (err) {
        return res.json({ success: false, message: 'Failed to authenticate token on API server.' });    
      } else {
        // if everything is good, save to request for use in other routes
        req.decoded = decoded;    
        next();
      }
    });
    console.log(aaa);
  } else {
    // if there is no token return an error
    return res.status(403).send({ 
        success: false, 
        message: 'No token provided.' 
    });    
  }

I got the token back on the server correctly. authorization: "Bearer ....."

But it cannot verify. I got JsonWebTokenError Invalid token.

Can anyone help point out what I missed?

Upvotes: 0

Views: 2046

Answers (1)

Shawn
Shawn

Reputation: 5260

sign() and verify() both have sync and async version. sign() sync produces a token string and async produces a token object. I used sync version of sign() so I need to use sync version to decode the token of string back. like this

  if (token) {
    try {
        var decoded = jwt.verify(token, 'superSecrete');
    } catch (err) {
        return res.json({ success: false, message: 'Failed to authenticate token on API server.' });
    }
    req.decoded = decoded;    
    next();
  } else {
    return res.status(403).send({ 
        success: false, 
        message: 'No token provided.' 
    });    
  }

Upvotes: 1

Related Questions