AngularJS Access Token Security Concerns - angularjs

What is the best practice for storing an access token in AngularJS after it is retrieved from an authorization server? I have seen many suggestions to use the localStorage service, but then I have read other posts/blogs that say to never use localStorage to store tokens, it is not secure etc.
I am having a hard time wrapping my head around security with Angular because of mixed information like above.

I think,
Generate the token (sensitive info at server side)
Sign and Encrypt the generated token with machine key which is only known to server. And get the encrypted token.
Then save the encrypted token obtained at step2 in cookies.
Cookies expiration should be very less. Make httponly cookie.
When authenticating the cookie
Validate the cookie
Decrypt with machine key and verify it is sent by our server only and with the same crc.
Authenticate the obtained token if step2 above is good.
Angularjs Automatically add headers in each $http request,
AngularAppFactory.GetApp=function(appName){
var app = angular.module(appName, []);
app.factory('httpRequestInterceptor', ['$rootScope', function($rootScope)
{
return {
request: function($config) {
if( $rootScope.user.authToken )
{
$config.headers['id'] = $rootScope.user.id;
$config.headers['auth-token'] = $rootScope.user.authToken;
}
return $config;
}
};
}]);
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});
return app;
}
//Whenever you need to get new angular app, you can call this function.
app = AngularAppFactory.GetApp('appName');

Related

CSRF token in angular is different of Laravel 5

I have a project split up in backend and frontend, the backend (API rest) is built in Laravel 5 and frontend in AngularJS. Both project are independent and they are supposed to be hosted on different servers.
In the first request I obtain the CSRF token from Laravel with this code:
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "http://laravel.local/api/token", false);
xhReq.send(null);
angular.module('mytodoApp').constant('CSRF_TOKEN',xhReq.responseText);
So the CSRF_TOKEN is sent each time that I make a request to API, like this:
$scope.deleteTodo = function(index) {
$scope.loading = true;
var todo = $scope.tours[index];
$http.defaults.headers.common['XSRF-TOKEN'] = CSRF_TOKEN;
console.log($http.defaults.headers.common['XSRF-TOKEN']);
$http.delete('http://laravel.local/api/deleteTodo/' + todo.id, {headers : {'XSRF-TOKEN': CSRF_TOKEN}})
.success(function() {
$scope.todos.splice(index, 1);
$scope.loading = false;
});
The API always return:
TokenMismatchException in compiled.php line 2440:
Is it right that Laravel changes the CSRF Token with every request from Angular? On every request, Laravel creates a new file on storage/framework/sessions. Do you recommend any other solution to validate that requests to API come from a safe origin?
In token-based authentication, cookies and sessions will not be used. A token will be used for authenticating a user for each request to the server.
It will use the following flow of control:
The user provides a username and password in the login form and clicks Log In.
After a request is made, validate the user on the backend by querying in the database. If the request is valid, create a token by using the user information fetched from the database, and then return that information in the response header so that we can store the token browser in local storage.
Provide token information in every request header for accessing restricted endpoints in the applications.
4.request header information is valid, let the user access the specified end point, and respond with JSON or XML.
This Can be Achieved by Jwt (Json web Token).got this information from This link.
So, what is this JWT?
JWT
JWT stands for JSON Web Token and is a token format used in authorization headers. This token helps you to design communication between two systems in a secure way. Let's rephrase JWT as the "bearer token" for the purposes of this tutorial. A bearer token consists of three parts: header, payload, and signature.
The header is the part of the token that keeps the token type and encryption method, which is also encrypted with base-64
The payload includes the information. You can put any kind of data like user info, product info and so on, all of which is stored with base-64 encryption.
The signature consists of combinations of the header, payload, and secret key. The secret key must be kept securely on the server-side.
The tutorial with example can be Found here Token-Based Authentication With AngularJS & NodeJS.
Hope that this will solve your problem,All the Best!!

Angular basic authentication and token

I'm getting crazy to understand how to handle a basic authentication with an API.
Basically what I need to do is to request a token from an API sending a module-username and module-password (not a user login). The server should return a token that I will need to use for all other request I will make to the server.
Looking on internet I've found solution that involves user logins and angular routing.
I'm not using any routing, the routing is managed server side and I need to consume the API on few pages, before consuming I need to attach the token to every request.
I don't understand exactly how to start properly.
I should need to create an ajax request for the first authentication, save the token somewhere and use it for all other requestes. Keeping in mind that if the token is not valid I should request it again.
I'm quite confused on how to do it, I can not find any good tutorial.
Any help?
I'm still learning Angular myself, but hopefully this basic example helps you. You can use $cookies to save and retrieve a token that is sent back from your server. Then, assuming you are using $http or $resource, you can use an $httpProvider interceptors to add the current token value (retrieved from $cookies) to the header of every outgoing request your app makes.
Here's a simple example of how you might create an $httpProvider interceptor:
authServices.factory('sendTokenInHeader', ['$cookies', function($cookies) {
return {
request: function(config) {
var token = $cookies.getObject('x-my-token');
if(token) {
var updateHeaders = config.headers || {};
updateHeaders['x-my-token'] = token;
config.headers = updateHeaders;
}
return config;
}
};
}]);
Then in your app.config you need to just push this interceptor and now any outgoing $http/$resource request will include the current token!
myApp.config(['$httpProvider', function($httpProvider) {
// do other stuff...
$httpProvider.interceptors.push('sendTokenInHeaders');
}]);

Get user role in clear text along with JWT when using AngularJs, WebAPI and OAuth2

I am sing OAuth2 in WebAPI project. I am authenticating user request in OWIN middleware. On successfull authentication I am sending an JWT access token to client. Now I can validate subsequent request at server and use [Authorize(Roles="myRole")] attribute on Api Controllers.
But how can I show validate client content in AngularJs and show pages based on user role? I have JWT at client and no idea how to get user role out of it?
Is it a good approach to extract information from JWT?
You will need to parse that JWT and get the values out. You can do that with the help of the angular-jtw library.
1) Download the angular-jwt.min.js (https://github.com/auth0/angular-jwt)
2) put a dependecy of "angular-jwt" on the application module:
var app = angular.module("YOUR_APP", ["angular-jwt"]);
3) pass the jwtHelper to your service or controller or wherever it is that you wish to use it.
app.module.factory("YOUR_SERVICE", function(jwtHelper){
...
});
4) use the decodeToken method of the jwtHelper you passed in to decode your token
For example, the code below is parsing out the role object from a jwt that came back from my service endpoint. Upon succssful return from the server the role is extracted from the jwt and returned.
return $http.post(serviceEndPoints.tokenUrl, data, config)
.then(function (response) {
var tokenPayLoad = jwtHelper.decodeToken(response.data.access_token);
//Now do whatever you wish with the value. Below I am passing it to a function: (determineRole)
var userRole = determineRoles(tokenPayLoad.role);
return userRole;
});
};
Hope that helps
//Houdini
Currently we don't offer anything that would help you to take advantage of that information on the client. Also note: as today we do not validate the token on the client, we cannot really trust its content... while the [Authorize] attribute on the server side gets the role info only after the pipeline before it had a chance of validating the signature and deciding that the token is valid.
We might introduce something that will help with this scenario in the future, but for the time being you'd need to write custom code or rely on the server side to echo things back.

Adding Custom Header in AngularJs upon bootstrapping

Suppose I have an angular app called chococalateApp that depends on 3 other modules, namely Product, Sales and LogIn.
Now, my app is building on RESTful API. Upon successful login, the server will respond by sending back an authentication token. I would like to append this token as a custom header X-AUTH whenever $http services are used. Since all my REST API requires the auth token, I would need to append this header in every $http request. This is doable by configuring the $httpProvider, as shown below:
angular.module('chocolateApp',['Product','Sales','Login'])
.config(['$httpProvider', function($httpProvider){
$httpProvider.defaults.headers.common['X-AUTH'] = 'randomkeybyserver'
}
])
My question is, can I inject the value of the auth-token AFTER the module has been bootstrapped?
For example, I have a service in LogIn module that is able to do the authentication, and retrieved the required token. How do I pass the token back to my main chocolateApp module and configure it? Will this result in circular dependency, or is it that my understanding of DI is wrong here?
If this is not achievable, how should this be designed?
You can do it from your Login service after authentication and it will be available across your app.
login: function(...) {
$http.post(...).then(function(response) {
$http.defaults.headers.common['X-AUTH'] = response.data.randomkeybyserver;
});
}

Authentication using Angularjs

I am fairly new to AngularJS
I have a resource that I use for user management which is part of a service following this article.
Once sending the login request to the server I am getting a response with a set-cookie as part of the header.
What is the best practice to add this cookie to every request I am sending to the server?
myApp.factory('UserService', ['$resource', function ($resource) {
var userRes = $resource('http://<MyDomain>/api/v1/user/:param',
{param: '#param'},
{
login: {
method: 'POST'
},
logout: {
method: 'DELETE'
}
});
var user;
return {
signIn: function () {
user = userRes.login({param: 'login'}, {"email": "SomeName#MyDomain.com", "password": "test1"});
userRes.get({param: '1'});
},
userRes.login has set-cookie header in on the response
userRes.get does not send the cookie that was just received.
Cheers
Since your API is in a different domain you can't use cookies in this case. We've tried and we failed to put it simple there is no way, not only it doesn't work with CORS but also it doesn't work if you embed an iframe. The iframe trick fails on safaris mostly but it is not reliable.
What we usually do is to return a JWT (Json Web Token) from the API and attach a header then to every API request as Authorization: Bearer JWT.
This JWT can be decoded using a public key from the front end (and it will contain the user profile) and validad with a private key in the backend.
JWT is simple and there are plenty of libraries for every language/technology.
Auth0 is an authentication broker that can validate with any identity provider or custom databases, and it returns JWTs using standars. It provides a clientID that can be used to decode the profile in the front end and a secret to validate the tokens in the backend as well as client side library to do this.
Disclaimer: I work for auth0.

Resources