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 ?
There is a
$cookies
service available in the AngularJS API using thengCookies
module. It can be used like below:For your case it would be:
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.Having the
http interceptor
in place you do not need to set theAuthorization header
for each request.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.I would advise against keeping the data in a cookie, for security purposes you should set the cookies to secure and HttpOnly (not accessible from javascript). If you're not using SSL, I would suggest moving to
https
.I would pass the token from the auth endpoint in a json response:
You can save the token data in
sessionStorage
by using the$window
service:It will be cleared once the user closes the page, and you can manually remove it by setting it to empty string:
Edit:
Interceptor implementation for catching data, adapted from cbass (not tested, you can inspect the objects for response/request to fiddle with the information):