0

I have an application that is using the standard jwt authentication shown below and copied from the express-jwt readme.

app.use(jwt({
  secret: 'hello world !',
  credentialsRequired: false,
  getToken: function fromHeaderOrQuerystring (req) {
    if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
        return req.headers.authorization.split(' ')[1];
    } else if (req.query && req.query.token) {
      return req.query.token;
    }
    return null;
  }
}));

When I hit the api, the authorization header is equal to 'Bearer hello world !'. This equals my secret, but I am getting a 401 unauthorized thrown. Does anyone have any idea why? isn't req.headers.authorization.split(' ')[1] supposed to equal the secret?

2 Answers 2

1

No the Bearer is not your secret. It's a base64 encoded jwt containing (header, payload and signature). The secret is used to sign the jwt payload with the algorithm specified in the jwt header.

Read the introduction on the official JWT website to understand this concept.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use JsonWebtoken npm package to implement jwt based authentication in your express App. This is how authentication works :

  • import jwt from the package

    const jwt = require('jsonwebtoken');

Set Token in login.service.js file or where ever required with appropriate data as payload :

 const token = jwt.sign('payload', 'secret key',
               { expiresIn: 60*60 });
   how token looks: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYW5pcyIsImVtYWlsIjoic29tZW1lYWlsLmNvbSIsImlhdCI6MTUxNjIzOTAyMn0.FyDrUNkvDi82lYv8JioAB9Ih8vyn6Y6mY8PpUiIz8nY 

You can decode it by pasting the token on jwt.io website.

  • Usually we store the token in cookies(before sending response in login.router.js file set the cookie as token) :

     router.get('/auth/google/callback', (req, res, next) => {
      loginCtrl.redirectGoogle(req, res, next).then((result) => {
         res.cookie('userToken', token);
        res.redirect('/#/app/home');
         }, (err) => { 
         console.log("Error in authentication **[ ", err, " ]** ");
      res.redirect(500, '/#/login');
    });  
    
  • now write a middleware(authentication) that is called before every API request(authentication.router.js file).

router.use((req, res, next) => {
  try {
    const token = req.cookies.currentUser;
       // console.log('cookie', token);
       // to  decode token
    if (token) {
      authCtrl.verifyToken(token, (err, decoded) => {
        if (err) {
          res.clearCookie(config.UserToken);
          res.status(401).json({ error: ' Session Timeout... Please login again' });
         // console.log('token expired');

         // res.redirect('/#/login');
        } else {
          req.user = decoded;
          next();
        }
               // console.log('Token verified');
               // res.cookie(config.cookie.name,successResult.authToken);
      });
    } else {
           // if there is no token
           // return an error
      return res.status(403).send({
        message: 'User not authenticated.',
      });
    }
  } catch (error) {
   // console.log(error);
    return error;
  }
});

  • Inside verifyToken function which is inside auth.controller.js file we decode the token :

const jwt = require('jsonwebtoken');

const verifyToken = (usertoken, done) => {
  jwt.verify(usertoken,'secret key', (err, res) => {
    if (err) {
      return done(err);
    }
    return done(null, res);
  });
};

module.exports = {
  verifyToken,
};

Now you API endpoints are are protected with authentication. Make sure The authentication middleware is place at top in app.js file.

router.use('/login', require('./modules/login'));
router.use('/logout', (req, res) => {
  res.clearCookie(userToken);
  res.redirect('/');
});
router.use(require('./modules/authentication'));
// Each Module to be placed after this
router.use('/communityMembers',require('./modules/communitymember'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.