[Q1] What advantage does an HTTP Interceptor provide on modifying the config.headers["Authorization"] (frontend AngularJS) to contain the value of token when I can verify the requests by checking the req.cookies object? (at the backend NodeJS)
I am trying to understand how JSON web tokens function. The demo application I have setup has a login functionality.
- On GET '/login' I am able to produce a token, set a cookie with it.
- On the frontend, I can access a JSON object containing the token.
- I can view the cookie in the developer console.
Nodejs:
index.js - login route
router.post('/login', function(req, res, next) {
Authenticator.find(req.cookies.token, req.body, Heartbeat.common, function(err, warning, data){
if(err) {
res.status(404).send({token:false, warning: null, error:err});
} else if(warning){
res.status(200).send({token:true, warning: warning, error:null});
} else {
res.cookie('token', data, {maxAge: 3600000, httpOnly:true});
res.status(200).json({token:true, error: null});
}
});
});
Authenticator.ctrl.js - Authenticator.find()
find: function(token, user, heartbeat, callback) {
if(!token) {
Auth.findOne({email:user.email}, function(err, data){
if(err) {
console.log(err);
} else {
if(data) {
if(data.checkHash(user.password)) {
callback(null, null,TokenMaker.createToken(user.email, heartbeat));
} else {
callback(Errors.login.strict.MISMATCH, null, null);
}
} else {
callback(Errors.login.strict.NOT_REGISTERED, null, null);
}
}
});
} else {
callback(null, Errors.login.warning.ACTIVE_REFRESH, null);
}
},
Angular Controller
app.controller('userAccessCtrl', ['$scope', '$http', function ($scope, $http){
$scope.user = {
email: "someone@some.com",
password: "12345679"
};
$scope.error = {};
$scope.loginAccess = function(user) {
var submitReady = true;
var emailStatus = EmailValidator.email(user.email);
var passwordStatus = EmailValidator.password(user.password);
if(typeof emailStatus === "string") {
$scope.error.email = emailStatus;
submitReady = false;
}
if(typeof passwordStatus === "string") {
$scope.error.password = passwordStatus;
submitReady = false;
}
if(submitReady) {
$scope.error = {}
var data = $scope.user;
$scope.user = {};
$http.post('/login', data)
.then(function(success){
console.log(success);
},function(error){
console.log(error);
});
}
}
}]);
Console response:
{
"data": {
"token":true,
"error":null
},
"status":200,
"config":{
"method":"POST",
"transformRequest":[null],
"transformResponse":[null],
"url":"/login",
"data":{
"email":"someone@some.com",
"password":"12345679"
},
"headers":{
"Accept":"application/json, text/plain, */*",
"Content-Type":"application/json;charset=utf-8"
}
},
"statusText":"OK"
}