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.
@Liw.S. test this: http://stackoverflow.com/a/18041849/2256325 I can add to the reply later when I get home.
– Sergio
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.
@Liw.S. I added examples in the reply
– Sergio
Oops, I think this will suit me. Thank you very much.
– Liw. S.
It occurred to me the doubt, as I would logout?
– Liw. S.