-
-
Save SergioCrisostomo/445e4e37a6972c8493e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var app = express(); | |
var jwt = require('jsonwebtoken'); // inserir o módulo jwt | |
var bodyParser = require('body-parser'); | |
// parse application/x-www-form-urlencoded | |
app.use(bodyParser.urlencoded({ extended: false })); | |
// parse application/json | |
app.use(bodyParser.json()); | |
app.use(function(req, res, next) { | |
res.header("Access-Control-Allow-Origin", "*"); | |
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-access-token"); | |
next(); | |
}); | |
app.set('superSecret', 'teste'); // criar uma palavra passe de controlo | |
var token = jwt.sign('user', app.get('superSecret'), { | |
expiresInMinutes: 1440 // expires in 24 hours | |
}); | |
console.log(token); // para usar no lado do cliente! | |
app.get('/', function (req, res) { | |
res.send('Hello World!'); | |
}); | |
// 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']; | |
console.log(req.headers) | |
// 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; | |
res.end('Bemv vindo!'); | |
} | |
}); | |
} 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); | |
var server = app.listen(3000, function () { | |
var host = server.address().address; | |
var port = server.address().port; | |
console.log('Example app listening at http://%s:%s', host, port); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "token-test", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"body-parser": "^1.14.0", | |
"express": "^4.13.3", | |
"jsonwebtoken": "^5.0.5" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<div id="resposta"> | |
</div> | |
<script type="text/javascript"> | |
function reqListener () { | |
document.getElementById('resposta').innerHTML = 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> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment