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