Reputation: 223
I'm building an app with Node.js + Express, and I'm trying to use JSON Web Tokens for authentication. Right now I am at the point where once a valid username/password is entered, the server responds by sending the client a JWT.
This is where I get lost.
How do I send that token along with further requests to the server?
How can I send it as a header?
Upvotes: 3
Views: 885
Reputation: 59
first you need to set the json token in client by using http cookie (res.cookie("token","yourtoken")) or using session
when user sends a request you need to send the token to server.you can read cookie by using req.cookie.token and verify it in middleware or use session
Upvotes: 1
Reputation: 2671
How do I send that token along with further requests to the server?
http://localhost:8080/api/users?token=tokenValue
document.cookie
to save token in your cookieHow can I send it as a header?
Using JQuery
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authorizationToken);
},
url: "entities",
data: "",
success: function(msg) {
}
});
At Server Side, you can do:
var token = req.body.token || req.query.token || req.headers['x-access-token'];
For Cookie Parsing, you can use: Cookie-Parser
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
Further Reading: https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens
Upvotes: 2
Reputation: 2603
client can set the access token either as header or query parameter or in request body. Following is a way to send via header:
$.ajax({
url: 'foo/bar',
headers: { 'x-access-token': 'some value' },
data: {}
}).done(function(result){
//do something
});
Best practice is to save the access-token in browser local storage rather than in cookie. Once you obtain the token once logged it.
Server, best way to include a authentication middleware above all secured routes, where token is required.
auth.middleware:
'use strict';
module.exports = function(req,res,next){
const jwt = require('jsonwebtoken');
const config = require('../config/config');
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secret, function(err, decoded) {
if (err) {
return res.status(401).json({ success: false, message: 'Failed to authenticate token.' });
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
};
routes:
//no token required
app.post('/signup',users.create);
app.post('/login',users.authenticate);
const auth = require('../middleware/auth.middleware');
//token required for below routes
app.use(auth);
app.get('/info',index.getInfo);
Upvotes: 1