如何使用AngularJS在浏览器cookie中存储身份验证承载令牌 [英] How to store authentication bearer token in browser cookie using AngularJS

查看:127
本文介绍了如何使用AngularJS在浏览器cookie中存储身份验证承载令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.net Identity创建了一个承载令牌。在AngularJS中,我写了这个函数来获取授权数据。

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 :(");
  });
};

所以我想将此令牌存储到浏览器cookie中。如果存在此令牌,则获取令牌并从IIS服务器获取数据,否则重定向到登录页面以登录以获取新令牌。

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.

同样,如果用户点击退出按钮,它应该从浏览器cookie中删除令牌。

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

怎么做?有可能吗?是否有正确的方式来验证和授权用户?如果有多个用户令牌怎么办?

推荐答案

使用
$ cookies 服务> ngCookies 模块。它可以像下面这样使用:

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 :(");
    });
};

您还必须添加 angular-cookies模块代码。并将其添加到角度应用程序: angular.module('myApp',['ngCookies']) ; Angular Cookies的文档。

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.

我还想建议使用 Http拦截器,它将为每个请求设置承载头,rath而不是必须为每个请求自己手动设置它。

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)

http拦截器到位不需要为每个请求设置授权标题

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']

如Boris所述:还有其他方法可以解决这个问题。您还可以使用 localStorage 来存储令牌。这也可以与http拦截器一起使用。只需将实现从cookie更改为localStorage。

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

这篇关于如何使用AngularJS在浏览器cookie中存储身份验证承载令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆