How to pass JWT via Header and retrieve data through Server Side Views in Sails.js
<p>Backend: Sails.js</p>

<p>I have already implemented JSON Web Token for the REST API, where all AJAX requests from the front-end to the actions of various controllers return data <code>res.json(data);</code> only if it receives a correct JWT via Authorization Header. It works as expected.</p>

<p>Now, i have created a view using EJS with <code>&lt;%= name =&gt;</code>, now a controller has the details <code>res.view('/home', {name: "Bill"} );</code> and configured the routes to point to the respective controller too.</p>

<p>How do i retrieve "name" from the controller by authenticating with an already issued JWT (stored in localStorage) from a Server Side View with the attribute <code>&lt;%= name =&gt;</code></p>

<p>Thanks.</p>

<p>CODE:</p>

<p>views/index.ejs</p>

<pre><code>&lt;%= name =&gt;
</code></pre>

<p>api/controllers/UsersController.js</p>

<pre><code>info: function(req, res) {

var userId = req.token;

Users.findOne(userId).exec(function(err, profile) {
    if(err) {
    res.json(err);
    } else {
       res.view('index',{
        name: profile.name,
    });
    }
});        
},
</code></pre>

<p>api/policies/tokenAuth.js</p>

<pre><code>module.exports = function(req, res, next) {
  var token;

  if (req.headers &amp;&amp; req.headers.authorization) {
    var parts = req.headers.authorization.split(' ');
    if (parts.length == 2) {
      var scheme = parts[0],
        credentials = parts[1];

      if (/^Bearer$/i.test(scheme)) {
        token = credentials;
      }
    } else {
      return res.json(401, {err: 'Format is Authorization: Bearer [token]'});
    }
  } else if (req.param('token')) {
    token = req.param('token');
    delete req.query.token;
  } else {
    return res.json(401, {err: 'No Authorization header was found'});
  }

  sailsTokenAuth.verifyToken(token, function(err, token) {
    if (err) return res.json(401, {err: 'Please Logout and Login again!'});

    req.token = token;

    next();
  });
};
</code></pre>

<p>api/services/sailsTokenAuth.js</p>

<pre><code>var jwt = require('jsonwebtoken');

module.exports.issueToken = function(payload) {
  var token = jwt.sign(payload, process.env.TOKEN_SECRET || "xxxxxxx");
  return token;
};

module.exports.verifyToken = function(token, verified) {
  return jwt.verify(token, process.env.TOKEN_SECRET || "xxxxxxx", {}, verified);
};
</code></pre>

<p>config/routes.js</p>

<pre><code>module.exports.routes = {
    '/': {
        controller: 'UsersController',
        action: 'info'
      },
};
</code></pre>

<p><strong>SOLUTION:</strong></p>

<p>To use JWT as an authenticating factor from client browser to server, either localStorage or session cookie can be used. I have finally narrowed it down to using the cookie since due to easier implementation in the server.</p>

<p>After authenticating the user, store the JWT in the clients browser,</p>

<pre><code>res.cookie('jwttoken', sailsTokenAuth.issueToken(profile.name));
</code></pre>

<p>Then it can be retrieved using <code>req.cookies.jwttoken</code> and verify it through a service (jwt.verify) to give access to requested information via <code>res.json</code> or <code>res.view</code></p>