我已经使用ASP.net Identity创建了承载令牌。在AngularJS中,我编写了此函数以获取授权数据。
$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服务器获取数据,否则重定向到登录页面以登录以获取新令牌。
同样,如果用户单击注销按钮,则应从浏览器cookie中删除令牌。
这该怎么做 ? 有可能吗?验证和授权用户的正确方法吗?如果有多个用户令牌怎么办?
$cookies使用该ngCookies模块的AngularJS API中提供了一项服务 。可以如下使用:
$cookies
ngCookies
function controller($cookies) { //set cookie $cookies.put('token', 'myBearerToken'); //get cookie var token=$cookies.get('token'); //remove token $cookies.remove('token'); } controller.$inject=['$cookies'];
对于您的情况将是:
//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的文档。
angular.module('myApp', ['ngCookies']);
我还想建议使用a Http interceptor,它将为每个请求设置承载头,而不是必须为每个请求手动设置它。
Http interceptor
//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 interceptor适当的位置后,您无需Authorization header为每个请求设置。
http interceptor
Authorization header
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。
localStorage
function controller($window) { //set token $window.localStorage['jwt']="myToken"; //get token var token=$window.localStorage['jwt']; } controller.$inject=['$window'];