How to set a token in the header?

Asked

Viewed 7,184 times

7

Well I use jwt to generate a token only that the example I was following didn’t show exactly how to paste the token into the application header. Would anyone know how? Note: I am using the express.

app.js /part of the main file

app.use(function (req, res, next) {
   res.setHeader('Access-Control-Allow-Origin', '*');
   res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
   res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
   next();
});

2 answers

4


You need to create a password and insert a middleware that checks and then make the http request with that token somewhere.

On the server side:

There’s a good example at this link with the main steps are:

require the jwt and set up a password

var express = require('express');
var app = express();
var jwt = require('jsonwebtoken'); // inserir o módulo jwt
    
app.set('superSecret', 'minha palavra passe'); // criar uma palavra passe de controlo

generate a token

Within the function/path that has the login logic, that is when you want to return a token to a user that is already verified you can do so:

var token = jwt.sign('nome do utilizador ou objeto', app.get('superSecret'), {
  expiresInMinutes: 1440 // validade de 24 horas
});

// mostrar o token ao utilizador com um JSON
res.json({
  success: true,
  message: 'Enjoy your token!',
  token: token // este token é para guardar!
});

set up a middleware to check the token

Finally you have to decide a middleware that runs in all the path you need, ie the url that should be protected. That part is closed in the last line of this code, first times of closing the router:

// ir buscar uma instância do router do Express.js
var apiRoutes = express.Router(); 

// middleware
apiRoutes.use(function(req, res, next) {

  // procurar a propriedade token em partes diferentes do pedido
  var token = req.body.token || req.query.token || req.headers['x-access-token'];

  // descodificar caso haja um valor no request
  if (token) {

    // verifies secret and checks exp
    jwt.verify(token, app.get('superSecret'), function(err, decoded) {      
      if (err) { // erro!
        return res.json({ success: false, message: 'Failed to authenticate token.' });    
      } else {
        // tudo ok! vamos passar esse valor para o req.decoded para ser usado no resto da aplicação
        req.decoded = decoded;    
        next();
      }
    });

  } else {

    // se não houver token no pedido/request, retornar erro
    return res.status(403).send({ 
        success: false, 
        message: 'No token provided.' 
    });
    
  }
});


// defenir quais os caminhos que devem estar protegidos
app.use('/api', apiRoutes);

On the client side

There are several options:

via form/POST

in this case just do a hidden input with the token:

<input type="hidden" name="token" value="eyJhbGciOiJIUzI1NiJ9.dXNlcg.EvNc9eWXXeAjpMTMzV4xoW2EjtEcLeSwJwY5_8vE6X8" />

and the express will be met with the req.body.token. (Don’t forget to join the middleware body parser)

via url/query string

In this case just join a query string with the url ?token=xxxxx, example:

http://localhost:3000/api?token=eyJhbGciOiJIUzI1NiJ9.dXNlcg.EvNc9eWXXeAjpMTMzV4xoW2EjtEcLeSwJwY5_8vE6X8

to search in the Node can be used req.query.token

via request header/AJAX

In this case just pass via AJAX request header like this:

<script type="text/javascript">
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest();

    oReq.addEventListener("load", reqListener);
    oReq.open("GET", 'http://localhost:3000/api');
    oReq.setRequestHeader('x-access-token', 'eyJhbGciOiJIUzI1NiJ9.dXNlcg.EvNc9eWXXeAjpMTMzV4xoW2EjtEcLeSwJwY5_8vE6X8');
    oReq.send();
</script>

and on the Node to search with req.headers['x-access-token']


Example:

I created an example with 3 files here: https://gist.github.com/SergioCrisostomo/445e4e37a6972c8493e8

  • So I’m following an example similar to this, but my question is how to pass the value of the token to the pages Ex: req.body.token = to pass a field on the req.query.token page = to go through the url, req.headers['x-access-token'] = in this case pass in header, as I would set the token in header?

  • @Liw.S. test this: http://stackoverflow.com/a/18041849/2256325 I can add to the reply later when I get home.

  • So, from what I saw in this question they pass the token by input Hidden and it is well that the solution I found, just wanted to go through the header not to be so implicíto, but thanks for answering.

  • @Liw.S. I added examples in the reply

  • 1

    Oops, I think this will suit me. Thank you very much.

  • It occurred to me the doubt, as I would logout?

Show 1 more comment

1

I don’t use localStorage, what I do is the following:

  1. In the Javascript page I create a variable for the token.
  2. I send the authentication by ajax( I had forgotten to mention this before, I apologize for the misunderstanding).
  3. When authenticated, in the API, I create a token, with the Unix time (All milliseconds since 01/01/1970) of its creation and user encrypted in it. In the browser, I pass the token value to the variable in the javascript reserved for it and remove the element by which it came.
  4. When sending a request, I add the token again.
  5. In the API, I decode the token and check its validity.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.