0
我正在使用角度$資源來訪問API。在這種特殊情況下,使用自定義登錄操作,以便登錄用戶。
爲了保存身份驗證後API提供的令牌,我將攔截器附加到自定義登錄操作,該操作通過$ cookie簡單地將令牌保存到cookie中。
我使用的是攔截器,因爲我需要從應用程序的其他部分保存和更新該cookie。
問題是,cookie似乎不會持續。
如果我在保存後檢查值,我可以確認它存在,但只要我的$位置發生變化(就像登錄後渲染主頁一樣),cookie就會消失。
任何想法?
謝謝,D.
這裏是我的登錄服務,它使用一個自定義登錄動作和攔截
(function() {
'use strict';
//Login Service
// Authenticates a user
angular
.module('console')
.factory('LoginService', LoginService);
LoginService.$inject = ['$resource', 'Config', 'UserInfoInterceptor'];
function LoginService($resource, Config, UserInfoInterceptor) {
return $resource(Config.api_url + '/auth/', {},
{
login: {
method: 'POST',
url: Config.api_url + '/auth/login',
data: {type: "passwd"},
interceptor: UserInfoInterceptor,
headers: {
"accept": "application/json",
"content-Type": "application/json;odata=verbose"
}
}
});
}
})();
這裏是攔截器(即那裏的console.log,實際上寫的cookie價值),但是在去其他地方之後它就會丟失。
(function() {
'use strict';
angular
.module('console')
.factory('UserInfoInterceptor', UserInfoInterceptor);
UserInfoInterceptor.$inject = ['$resource', 'Config', '$q', '$location', '$cookies'];
function UserInfoInterceptor($resource, Config, $q, $location, $cookies) {
return {
// Save the received token
'response': function (response) {
var now = new Date();
// this will set the expiration to 30 days
var exp = new Date(now.getFullYear(), now.getMonth()+1, now.getDate());
// Set the cookie
$cookies.put('token', response.data.token, {expires: exp});
//This actually works!!
console.log($cookies.get('token'));
return response;
},
// Whatever is the failure, throw the user to the login page
'responseError': function (response) {
if (response.status === 401 || response.status === 403) {
$location.path('/login');
}
return $q.reject(response);
}
};
}
它永遠不會太晚 – AlainIb