3

I have a REST Api, and all endpoints must send a response when the user has an authentication token (I use the jwt token). everything works fine when I test my code using postman, but from front not working(session closes after OPTION request, and on the request header bearer token not set).

Authentication Middleware

module.exports = function(req, res, next) {
    const authorization = req.headers['authorization'];
    console.log(authorization);
    const token = authorization
      ? authorization.replace('Bearer ', '')
      : null;

    if (!token) 
      return res.status(403).send({ auth: false, message: 'No token provided.' });

    jwt.verify(token, config.secret, function(err, decoded) {      
      if (err) 
        return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });    

      req.userId = decoded.id;
      next();
    });
}

route

const Router                = require('express').Router;

//Authentication Middleware
const requireAuthentication = require('../middlewares/').Auth()

module.exports = () => {
  let router = new Router();
  router.use(requireAuthentication);
  router.use('/accounts', require('./account')());
  router.use('/projects', require('./projects')());
  return router;
};

with authentication https://i.stack.imgur.com/cAFw5.png

without authentication https://i.stack.imgur.com/VUuuv.png

Varuzh Ghazaryan
  • 41
  • 1
  • 1
  • 4

2 Answers2

1

The reason was in access headers

I add middleware in bootstrap file.

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

    if ('OPTIONS' === req.method) {
      res.send(200);
    }
    else {
      next();
    }
});
Varuzh Ghazaryan
  • 41
  • 1
  • 1
  • 4
0

Try to use Express Cors: https://github.com/expressjs/cors

Simple Usage (Enable All CORS Requests)

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

Read more about CORS here https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS