[英]Oauth 2.0 token based authentication AngularJS (Beginner)
我已經瀏覽了多個文檔,包括ng-cordova和oauth-ng,但是我仍然找不到在angularjs / Ionic中處理基於基本令牌的身份驗證的任何資源。
我在如何在angularjs中進行這個curl調用時遇到麻煩
curl -X POST -vu sampleapp:appkey http://sampleurl/oauth/token -H "Accept: application/json" -d "password=pwd&username=sampleuname&grant_type=password&scope=read%20write&client_secret=appkey&client_id=sampleapp"
我正在這樣做,這給我一個401
錯誤。 但是,curl調用可以正常工作。
$scope.login = function() {
$http({
method: "post",
url: "http://sampleurl/oauth/token",
data: "client_id=" + clientId + "&client_secret=" + clientSecret + "password=pwd&username=sampleuser&grant_type=password" + "&scope=read%20write",
withCredentials: true,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
})
.success(function(data) {
accessToken = data.access_token;
$location.path("/secure");
})
.error(function(data, status) {
alert("ERROR: " + data);
});
}
我意識到,一旦獲得令牌 ,我必須做類似的事情
$http.get('http://apiurl/api/v1/users',
{headers: { Authorization: ' Token api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxx'}})
.then(function(response) {
service.currentUser = response.data.user;
console.log(service.currentUser);
});
但是到目前為止,我還無法找到一種方法來調用服務器並將訪問令牌保存在我的本地存儲中。 互聯網上的所有資源主要用於第三方登錄(google,facebook,twitter等)或JWT令牌。
我當時還很陌生,但是我發現我需要擔心密碼授予流程,在該流程中,用戶將其憑據提供給使用者,而使用者將這些憑證交換為訪問和刷新令牌。 我仍然不相信自己打的正確。
更新:正如下面的答案中的@DanielCottone所述,oauth-ng似乎是一個很好的解決方案,但是我看到的他們的文檔使我感到困惑,因為我也想將用戶名和密碼發送到url,並且示例未實現我能說的是它嗎?
這就是他們的文檔中的內容:
<oauth
site="http://oauth-ng-server.herokuapp.com"
client-id="d6d2b510d18471d2e22aa202216e86c42beac80f9a6ac2da505dcb79c7b2fd99"
redirect-uri="http://localhost:9000"
profile-uri="http://oauth-ng-server.herokuapp.com/api/v1/me"
scope="public">
</oauth>
同樣,這是我第一次嘗試進行任何形式的集成,因此我認為該呼叫將隨其發送憑據是有意義的嗎? 我該如何發送呢?
解決此問題的最佳方法是在身份驗證后將令牌存儲在localStorage中,然后使用攔截器將令牌注入到請求標頭中:
$ http身份驗證承諾 (您需要注入$ localStorage)
.success(function(data) {
$localStorage.accessToken = data.access_token;
$location.path("/secure");
})
認證攔截器
.factory('AuthInterceptor', function ($q, $localStorage, $rootScope) {
return {
request: function (config) {
if ($localStorage.access_token) {
config.headers['Authorization'] = 'Token api_key=' + $localStorage.token;
}
return config;
},
responseError: function (response) {
if (response.status === 401 || response.status === 403) {
delete $localStorage.access_token;
// Do some kind of redirect to login page here...
}
return $q.reject(response);
}
};
});
要注銷,您只需從localStorage刪除令牌,如果您從API獲得401或403,則所有其他請求都將重定向到登錄頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.