【问题标题】:manage authentication with tokens created with OAuth2 in angular.js使用 angular.js 中使用 OAuth2 创建的令牌管理身份验证
【发布时间】:2015-07-07 07:02:37
【问题描述】:

我的消息是基于此消息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;} }; }]);

但这是我在控制台中得到的:

感谢帮助

【问题讨论】:

    标签: javascript angularjs symfony


    【解决方案1】:

    您必须有角度才能使用令牌拦截器。这可以在应用配置阶段完成

    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/

    希望对你有帮助

    【讨论】:

    • 感谢 Chintana Meegamarachc,我已将这些行添加到我的配置文件中:感谢 Chintana Meegamarachc,我已将这些行添加到我的配置文件中:.config(['$httpProvider',function ($httpProvider) { $httpProvider.interceptors.push('TokenInterceptor'); }]) 但我收到此错误:未捕获错误:[$injector:unpr] 未知提供者:TokenInterceptorProvider
    • 能不能改成$httpProvider.interceptors.push("authorizationInterceptor");
    • 总是同样的问题 :( -> 未捕获错误:[$injector:cdep] 找到循环依赖项:$http
    • 这可能是因为您使用“安全”服务作为拦截器的依赖项,并且拦截器在执行 http 调用时是从安全服务调用的。最好的办法是创建另一个服务来保存令牌并将其与“安全”服务和拦截器一起使用
    【解决方案2】:

    使用这样的令牌拦截器:

    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');
    

    【讨论】:

    • 感谢@Viki 和控制器,我应该从控制器调用服务吗??
    • 你不需要调用任何东西,一旦你添加了 $httpProvider.interceptors.push('TokenInterceptor');如果会话存储具有令牌,则每个请求都将在标头中注入令牌。看看@Chintana Meegamarachchi 如何在 $httpProvider 中推送拦截器。抱歉,stackoverflow 新手,不习惯这个编辑器。
    猜你喜欢
    • 2015-01-01
    • 2021-05-12
    • 2015-03-28
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    相关资源
    最近更新 更多