Angular basic authentication and token - angularjs

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');
}]);

Related

How can i get token from identity server 4 from angular js?

I can get get access token from postman oauth 2. Same way i was
tried to generate token in angular js with redirect url, client id
... etc.
But i not able to do and also i don't know how?
I was created identity server 4 API sample with auth server. Now i
want to get token from my angular app.
But i need this flow in angular js.
I tried this below code
angular.module("trainingApp")
.controller('loginController', ['$scope', function ($scope) {
function login(){
var client_id="testproduct";
var client_secret="test#123";
var scope="testAPI";
var redirect_uri="http://localhost:9000";
var response_type="token";
var url="http://localhost:1215/connect/authorize?scope="+scope+"&client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri=http://localhost:9000"+redirect_uri+"&grant_type=authorization_code"+
"&response_type="+response_type;
window.location.replace(url);
};
login();
}])
Access to XMLHttpRequest at 'localhost:1215/connect/…' from origin 'localhost:9000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
But i am get UI for Login. Help ???? :)
You're on the right track with the authorize endpoint redirect but you're doing it the hard way.
Check out the oidc-client-js library, it does everything you need and there are even samples for Angular.
https://github.com/IdentityModel/oidc-client-js

How to use two separate $http service instances in AngularJS?

I am implementing an angularjs service, which saves the data sent by an $http call in localStorage. In order to do that, I am using the request interceptor, so that whenever an http request is sent via $http, the data is saved in localStorage. Below is my code for the interceptor,
var OfflinkJs = angular.module('OfflinkJs', []);
OfflinkJs.factory('cacheInterceptor', function () {
var cacheInterceptor = {
request: function (config) {
// Here I am saving the config as a string in localstorage
return config;
}
};
return cacheInterceptor;
});
For above interceptor to work, I have to register it in the interceptors array of $httpProvider. I have done this to achieve that,
OfflinkJs.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('cacheInterceptor');
}]);
PROBLEM
Now, when I use OfflinkJS module in another module, all the $http calls go through my interceptor. But I would like to make some requests sent by $http service use my interceptor while some other requests NOT.
Since $http service is a singleton, I cannot figure out how to use two instances of it in separate places of my application. Is there any way to achieve this?
I went through this question, but seems it really addresses the issue of Circular dependency
I need two instances of AngularJS $http service or what?
I check the URL in the interceptor and use that to filter out requests to other services. I set the base url for my service as a constant in my module, and then check against that. If the request isn't to the relevant service, it just passes through with no action.
But perhaps a better way would be to set up a data service instead of an interceptor. There are plenty of tutorials out there on data services.

AngularJS Access Token Security Concerns

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');

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;
});
}

Angular ui-router using resolve validate authentication

I'm trying to see what's the best way to validate if a user is authenticated into the application.
Right now I'm using the following:
The user log in into the application
On Server Side a Token is created and send it back to the browser
On Log In Success, AngularJS stores the Token: $http.defaults.headers.common['RequestVerificationToken'] = token || $cookies.token;
On every http call to the server the Token is sent and is verified server side, in case the token doesn't exist then a 401 response status is sent to client.
This is working pretty well, now Im using UI-Router to control application states (pages - real scenario):
I have the following state:
$stateProvider
.state('personinfo', {
url: "/personinfo",
controller: 'PersonController',
templateUrl: "app/partials/personinfo.html"
})
Inside my PersonContoller:
app.controller('PersonController', function ($scope,$sce, $location, PersonService) {
$scope.title = 'Person Page';
PersonService.getPersons().success(function (response) {
$scope.persons = response.success;
}).error(function () {
// If token doesn't exist, a 401 reponse status is sent by server
$location.url('/login');
});
});
I don't really like how it works because AngularJS will load the state and download the partial HTML file and then it will go into the controller and execute the get method and if the token is not valid then it will redirect to login state.
I would like to validate the token before the state is being loaded, so if the token is not valid then the partial HTML won't be downloaded or whatever.
I have read that UI-Router has a resolve property that can be used to get data before the view is loaded... can I use the resolve to validate the Token?
Hope someone can give me a guide or advice.
Thanks a lot.
Your build stack should compile production JS with template embedded, so there
is no round trip to worry about.
If you really want to intercept the initial page load, experiment with
$locationChangeSuccess, which is fired before the first $routeChangeStart.
If you want to hook into resolve, just attach a promise to it.

Resources