可以使用AngularJS的ngCookies模块来实现在Cookies中存储和管理JWT令牌。
首先,需要在应用程序中导入ngCookies模块:
angular.module('myApp', ['ngCookies']);
然后,在登录成功后,可以将JWT令牌存储到Cookies中:
app.controller('LoginCtrl', function($scope, $http, $cookies, $location) {
$scope.login = function() {
$http.post('/login', $scope.user).then(function(response) {
// 存储JWT令牌
$cookies.put('access_token', response.data.access_token);
// 跳转到主页
$location.path('/home');
}, function(error) {
// 处理错误
});
};
});
接下来,在每个HTTP请求中,可以使用拦截器来将JWT令牌注入到Header中:
app.factory('authInterceptor', function($q, $cookies) {
return {
request: function(config) {
var token = $cookies.get('access_token');
if (token) {
config.headers.Authorization = 'Bearer ' + token;
}
return config || $q.when(config);
}
};
});
app.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
这样,在每个HTTP请求中,都会自动注入JWT令牌,并将其发送到服务器端。