How do I set a token in the header?

6

Well I use jwt to generate a token only because the example I was following did not show exactly how to collocate the token in the application header. Would anyone know how? Note: I'm using 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();
});
    
asked by anonymous 23.09.2015 / 04:46

2 answers

2

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

On the server side:

There is a good example this link with the steps are:

require 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

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

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!
});

configure a middleware to check the token

Finally you have to define a middleware that runs on all the path you need, ie the url that should be protected. This part is defined in the last line of this code, first times to define 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 make a hidden input with the token:

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

and the expression will be found with req.body.token . (Do not forget to join middleware body parser )

via url / query string

In this case, just add a query string with ?token=xxxxx , for example:

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

To get the Node you can use req.query.token

via request header / AJAX

In this case, just pass through 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 in the Node go fetch with req.headers['x-access-token']

Example:

I've created an example with 3 files here: link

    
23.09.2015 / 07:02
1

I do not use the localStorage, what I do is the following:

  • In the Javascript of the page I create a variable destined for the token.
  • I have sent authentication to ajax (I forgot to mention this before, I apologize for the misunderstanding).
  • When authenticated, in the API, I create a token, with the Unix time (Every millisecond since 01/01/1970) of your creation and user encrypted on it. In the browser, I pass the value of the token to the variable in the javascript reserved for it and remove the element it came from.
  • When submitting a request, I add the token again.
  • In the API, decode the token and check its validity.
  • 04.02.2016 / 22:33