Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  38] [ 7]  / answers: 1 / hits: 46844  / 9 Years ago, thu, december 31, 2015, 12:00:00

I have created a bearer token using ASP.net Identity. In AngularJS I wrote this function to get authorized data.



$scope.GetAuthorizeData = function () {
$http({
method: 'GET',
url: /api/Values,
headers: { 'authorization': 'bearer <myTokenId>' },
}).success(function (data) {
alert(Authorized :D);
$scope.values = data;
}).error(function () {
alert(Failed :();
});
};


So I want to store this token into Browser cookies. If this token is present there , then take the token and get the data from IIS server Otherwise redirect to login page to login to get a new token.



Similarly, if user click onto log out button, it should remove the token from browser cookie.



How to do this ? It it possible ? Is it proper way to authenticate and authorize a user ? What to do if there are multiple users token ?


More From » angularjs

 Answers
39

There is a $cookies service available in the AngularJS API using the
ngCookies module. It can be used like below:



function controller($cookies) {
//set cookie
$cookies.put('token', 'myBearerToken');

//get cookie
var token=$cookies.get('token');

//remove token
$cookies.remove('token');
}
controller.$inject=['$cookies'];


For your case it would be:



//inject $cookies into controller
$scope.GetAuthorizeData = function () {
$http({
method: 'GET',
url: /api/Values,
headers: { 'authorization': 'bearer <myTokenId>' },
})
.success(function (data) {
$cookies.put('token', data);
}).error(function () {
alert(Failed :();
});
};


You will also have to add the angular-cookies module code. And add it to your angular app: angular.module('myApp', ['ngCookies']);. Docs for Angular Cookies.



I would also like to suggest the usage of a Http interceptor which will set the bearer header for each request, rather than having to manually set it yourself for each request.



//Create a http interceptor factory
function accessTokenHttpInterceptor($cookies) {
return {
//For each request the interceptor will set the bearer token header.
request: function($config) {
//Fetch token from cookie
var token=$cookies.get['token'];

//set authorization header
$config.headers['Authorization'] = 'Bearer '+token;
return $config;
},
response: function(response) {
//if you get a token back in your response you can use
//the response interceptor to update the token in the
//stored in the cookie
if (response.config.headers.yourTokenProperty) {
//fetch token
var token=response.config.headers.yourTokenProperty;

//set token
$cookies.put('token', token);
}
return response;
}
};
}
accessTokenHttpInterceptor.$inject=['$cookies'];

//Register the http interceptor to angular config.
function httpInterceptorRegistry($httpProvider) {
$httpProvider.interceptors.push('accessTokenHttpInterceptor');
}
httpInterceptorRegistry.$inject=['$httpProvider'];

//Assign to module
angular
.module('myApp')
.config(httpInterceptorRegistry)
.factory('accessTokenHttpInterceptor', accessTokenHttpInterceptor)


Having the http interceptor in place you do not need to set the Authorization header for each request.



function service($http) {
this.fetchToken=function() {
//Authorization header will be set before sending request.
return $http
.get(/api/some/endpoint)
.success(function(data) {
console.log(data);
return data;
})
}
}
service.$inject=['$http']


As stated by Boris: there are other ways to solve this. You could also use localStorage to store the token. This can also be used with the http interceptor. Just change the implementation from cookies to localStorage.



function controller($window) {
//set token
$window.localStorage['jwt']=myToken;

//get token
var token=$window.localStorage['jwt'];
}
controller.$inject=['$window'];

[#63884] Tuesday, December 29, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aileent

Total Points: 556
Total Questions: 107
Total Answers: 101

Location: Croatia
Member since Fri, Sep 11, 2020
4 Years ago
;