Matoy Matoy - 2 months ago 7
AngularJS Question

$http request is passed to the server in angular js without specify it on the client side

I saw a demo of an authentication using angular js and JWS auth02 metodología and I refocterd it a little...
I am using express (node js) on the server side to define myApp.

my question is this - on the client side I am doing this http GET call:

$http({url: '/api/restricted', method: 'GET'})
.success(function (data, status, headers, config) {
$scope.message = $scope.message + ' ' + data.name;
})
.error(function (data, status, headers, config) {
alert(data);
});


on the server side I am getting the id from the http GET request:

app.get('/api/restricted', function (req, res) {
res.json({
name: req.user.id
});
});


and it is working.. the only problem is that I don't see where I defined a GET request with a user entity... all I see is that the GET http request get a method and a url:

$http({url: '/api/restricted', method: 'GET'})


so where is this magic
name: req.user.id


is coming from?

Thanks...

more of the code (may be relavent...):

index. html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Angular Authentication</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="./auth.client.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-cookies.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="UserCtrl">
<span ng-show="isAuthenticated">{{welcome}}</span>
<form ng-show="!isAuthenticated" ng-submit="submit()">
<input ng-model="user.username" type="text" name="user" placeholder="Username" />
<input ng-model="user.password" type="password" name="pass" placeholder="Password" />
<input type="submit" value="Login" />
</form>
<div>{{error}}</div>
<div ng-show="isAuthenticated">
<a ng-click="callRestricted()" href="">Shh, this is private!</a>
<br>
<div>{{message}}</div>
<a ng-click="logout()" href="">Logout</a>
</div>
</div>
</body>
</html>


client side

myApp.controller('UserCtrl', ["$scope", "$http","$window","$cookies", function ($scope, $http, $window,$cookies) {
$scope.callRestricted = function () {
$http({url: '/api/restricted', method: 'GET'})
.success(function (data, status, headers, config) {
$scope.message = $scope.message + ' ' + data.name;
})
.error(function (data, status, headers, config) {
alert(data);
});
};

myApp.factory('authInterceptor',["$rootScope", "$q","$cookies",
function ($rootScope, $q,$cookies) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($cookies.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookies.get('token');
}
return config;
},
responseError: function (rejection) {
if (rejection.status === 401) {
// handle the case where the user is not authenticated
}
return $q.reject(rejection);
}
};
}]);

myApp.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});


and this code on the server side:

var express = require('express');
var bodyParser = require('body-parser');

var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');

var secret = 'ssasDSA223Sasdas2sdsa23123dvxcgyew231';

var app = express();

// We are going to protect /api routes with JWT
app.use('/api', expressJwt({secret: secret}));

app.use(bodyParser.json());
app.use('/', express.static(__dirname + '/'));

app.use(function(err, req, res, next){
if (err.constructor.name === 'UnauthorizedError') {
res.status(401).send('Unauthorized');
}
});

app.post('/authenticate', function (req, res) {
//TODO validate req.body.username and req.body.password
//if is invalid, return 401
if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
res.status(401).send('Wrong user or password');
return;
}

var profile = {
first_name: 'John',
last_name: 'Doe',
email: 'John.Doe@gmail.com',
id: 333333333
};

// We are sending the profile inside the token
var token = jwt.sign(profile, secret, { expiresInMinutes: 60*5 });
res.json({ token: token });
});

app.get('/api/restricted', function (req, res) {
res.json({
name: req.user.id
});
});

app.listen(8080, function () {
console.log('listening on http://127.0.0.1:8080');
});

Answer

It appears that you are using the express-jwt library. Per the documentation, the express-jwt library is Middleware that validates JsonWebTokens and sets req.user.

This occurs when the middleware is invoked on this line: app.use('/api', expressJwt({secret: secret}));