[英]manage authentication with tokens created with OAuth2 in angular.js
我的消息基于此消息http://stackoverflow.com/questions/26748106/how-to-manage-authentication-with-token-in-angular-js我有一个PHP5后端(Symfony2),一个前端(angularJS)我已经成功地使用后端创建了令牌,但是我遇到了angularjs的问题,我必须从URL中获取令牌并将其放入每个请求中,以获取每个示例的客户端列表,这就是我所做的:
控制器:signin.js
'use strict';
// signin controller
app.controller('SigninFormController', ['$scope','$http', '$state','$localStorage','authorizationInterceptor', function($scope, $http, $state,$localStorage,authorizationInterceptor) {
$scope.user = {};
$scope.authError = null;
$scope.login = function() {
$scope.authError = null;
// Try to login
$http({method: 'POST', url: 'myURL/oauth/v2/token?client_id=clientID&client_secret=clientSecret&grant_type=client_credentials'})
.success(function(response){
if (response.data.user) {
$scope.errors.splice(0, $scope.errors.length);
$scope.msgs.splice(0, $scope.msgs.length);
$scope.posts = data; // response data
var token = this.$window.sessionStorage($scope.posts.access_token);
console.log(""+token);
console.log("success");
$state.go('app.home');}
})
.error(function(data, status, headers, config) {
$scope.authError = 'Email or Password not right';
console.log("data error ...");
});
};
和我的服务:access-services.js
.factory('Security', ['$http', function ($http) {
var token;
function login(email, password) {
return $http.post('/auth/login', {email: email, password: password})
.then(function (response) {
if (response.data.token) {
token=response.data.token;
}
});
}
function getToken(){
return token;
}
return {
login:login,
token:getToken
}; }])
.factory('authorizationInterceptor', ['Security', function (Security) {
return {
request: function (config) {
var token=Security.getToken();
config.headers = config.headers || {};
if (token) {
config.headers.Authorization = 'Bearer ' + token;
}
return config;} }; }]);
但这是我在控制台中得到的:
感谢帮助
使用这样的令牌拦截器:
app.factory('TokenInterceptor', function($q, $window) {
return {
request: function(config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers['X-Access-Token'] = $window.sessionStorage.token;
config.headers['X-Key'] = $window.sessionStorage.user;
config.headers['Content-Type'] = "application/json";
}
return config || $q.when(config);
},
response: function(response) {
return response || $q.when(response);
}
};
});
然后像这样在您的app.config中使用它
$httpProvider.interceptors.push('TokenInterceptor');
您必须一定要使用令牌拦截器。 这可以在应用配置阶段完成
yourApp.config(function($httpProvider) {
$httpProvider.interceptors.push("authorizationInterceptor");
});
我建议您阅读以下系列文章。 尽管它们是针对ASP.net MVC编写的,但所提供的概念是通用的
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.