【问题标题】:Using Passport for Authentication of API Endpoints使用 Passport 对 API 端点进行身份验证
【发布时间】:2016-07-28 15:09:18
【问题描述】:

coupletutorials 使用 jsonwebtoken、passport 和 passport-local 添加身份验证之后,我一直坚持将其集成到 my project。我想要它,以便对任何 API 端点的任何请求都需要身份验证,并且对触及 API 的前端的任何请求都需要身份验证。

现在发生的情况是我可以让用户登录并注册,但一旦他们登录,他们仍然无法访问需要身份验证的页面。用户收到 401 错误。就像令牌没有在请求中正确传递一样。

我也尝试添加“身份验证拦截器”

myApp.factory('authInterceptor', function ($rootScope, $q, $window) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
      }
      return config;
    },
    response: function (response) {
      if (response.status === 401) {
        // handle the case where the user is not authenticated
      }
      return response || $q.when(response);
    }
  };
});

myApp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
});

但这似乎也没有用。
我忘记或错过了什么?

编辑:

输入凭据并单击登录后,我在 chrome 控制台中收到此错误

GET http://localhost:3030/members/ 401 (Unauthorized)

但在我成功通过身份验证后,我的导航链接显示应有的
我也在运行 Node 的终端中收到此错误

UnauthorizedError: No authorization token was found
    at middlware (/ncps-mms/node_modules/express-jwt/lib/index.js)
    ...

编辑:

当我注入我的auth 对象时,这与我的服务器路由的this line 有很大关系。基本上我认为我的身份验证令牌没有通过我的GET 请求发送。但我认为当我将身份验证对象传递给 GET 请求时会发生这种情况。

编辑:

添加了 GET 请求的图片。

编辑/更新:

我相信我已经解决了身份验证问题,但我的成员视图状态问题在身份验证后仍然无法呈现。我有pushed my latest changes to github,如果你提取最新的并运行,你会看到你可以进行身份​​验证,但单击 View 链接无法加载视图。

【问题讨论】:

  • 你有没有调试检查你是否进入了 if than 在标题周围?
  • @Walfrat 我不明白你在问什么。
  • 你是不是用了浏览器的debogger,下个断点看看configer.header.Authorization这行是否被执行了?
  • 我已经取得了一些进展,但即使通过身份验证,我的视图仍然无法呈现。请查看我对 OP 的更新。
  • 两件事:在您的登录中,您同时使用 .error 和 .thne 功能。通常你要么使用 .succes/.error 要么使用 .then(successCallback, errorCallback)。不知道会不会有什么麻烦。其次,您应该执行一个 angular.run,它将为所有 ui-router 事件添加侦听器,以便您能够跟踪您的状态错误。

标签: angularjs passport.js passport-local json-web-token express-jwt


【解决方案1】:

https://github.com/gh0st/ncps-mms 在为解决问题进行了一些修复后对我来说工作正常...

https://github.com/gh0st/ncps-mms/pull/2

client/src/routes.js

/* jshint esversion: 6 */
/* jshint node: true */
import angular from 'angular';
import 'angular-ui-router';

angular.module('ncps.routes', ['ui.router'])
.config(($stateProvider, $urlRouterProvider) => {
    $urlRouterProvider.otherwise('/members/login');

    $stateProvider
    .state('login', {
        url: '/members/login',
        templateUrl: 'members/members-login.html',
        controller: 'AuthController',
        onEnter: ['$state', 'auth', function($state, auth) {
            if (auth.isLoggedIn()) {
                console.log('Going to /members/...');
                $state.go('members', {
                    // 'headers': {
                    //     'Authorization': 'Bearer ' + auth.getToken()
                    // }
                });
            }
        }]
    })
    .state('register', {
        url: '/members/register',
        templateUrl: 'members/members-register.html',
        controller: 'AuthController',
        onEnter: ['$state', 'auth', function($state, auth) {
            if (auth.isLoggedIn()) {
                $state.go('members');
            }
        }]
    })
    .state('members', {
        url: '/members',
        templateUrl: 'members/members-view.html',
        resolve: {
            members: function($http, auth) {
                console.log('Trying to get /members....');
                return $http.get('/members', {
                    headers: {
                        'Authorization': 'Bearer ' + auth.getToken()
                    }
                }).then(function(response){
                    return response.data;
                });
            }
        },
        controller: 'MembersController as membersCtrl'
    })
    .state('new', {
        url: '/members/add',
        templateUrl: '/members/members-add.html',
        controller: 'MembersSaveController as newMemberCtrl'
    })
    .state('test', {
        url: '/members/test',
        template: 'This is a test.'
    });
});

client/src/controllers/controllers.js

/* jshint esversion: 6 */
/* jshint node: true */
import angular from 'angular';
angular.module('ncps.controllers', [])

.controller('MembersController', ['$http', 'auth', 'members', function($http, auth, members) {
    console.log('Members retrieved');
    this.members = members;
}])

.controller('MembersSaveController', function($stateParams, $state, $http) {
    this.member = $state.member;

    this.saveMember = function(member) {
        $http.post('/members', member).then((res, member) => {
            $state.go('members');
        });
    };
})

.controller('NavController', ['$scope', 'auth', function($scope, auth) {
    $scope.isLoggedIn = auth.isLoggedIn;
    $scope.currentUser = auth.currentUser;
    $scope.logOut = auth.logOut;
}])

.controller('AuthController', ['$scope', '$state', 'auth', function($scope, $state, auth) {
    $scope.user = {};

    $scope.register = function() {
        auth.register($scope.user).error(function(error) {
            $scope.error = error;
        }).then(function() {
            $state.go('members');
        });
    };

    $scope.logIn = function() {
        auth.logIn($scope.user).error(function(error) {
            $scope.error = error;
        }).then(function() {
            $state.go('members');
        });
    };

    $scope.logOut = function() {
        auth.logOut().error(function(error) {
            $scope.error = error;
        }).then(function() {
            $state.go('members');
        });
    };
}]);

【讨论】:

  • 您能解释一下发生了什么以及为什么添加/修改您的代码可以解决问题吗?
  • resolve 正在尝试注入 members,但要做到这一点,必须将其声明为 MembersController 控制器上的最后一个参数......此外,auth 在那里不存在并且默默地失败了headers: { 'Authorization': 'Bearer ' + auth.getToken() } +1 ? :)
【解决方案2】:

抱歉,实际上没有时间调试问题,但我怀疑您的问题可能与您的 HTTP 请求的标头有关。

查看我的 chrome 浏览器生成的跟踪,您的客户端当前没有向 HTTP 请求标头提供“授权”键值对?

类似的东西;

密钥:授权 值:承载 [TOKEN_VALUE]

通过向 http 请求提供标头中指定的授权键/值对尝试使用 Postman REST 应用程序进行调试,并且服务器可以告诉我我试图提供的令牌值是格式错误的 Json Web 令牌。

而如果我拿走授权键/值对(这是您的客户用来通信的东西,我可能会重现同样的错误。

您可能想尝试修改您的客户端以包含授权密钥并查看它是否有效。如果没有,请告诉我,然后我们可以看看其他解决方案。

查看我的邮递员截图。

【讨论】:

  • 所以这绝对是问题所在。使用邮递员,如果我提供授权标头和“Bearer [token]”,我就可以访问我的 API。但是我如何将其输入到我的逻辑中呢?不是在这里处理吗? github.com/gh0st/ncps-mms/blob/master/client/src/…
  • 很高兴知道这个问题。今天早上试图通过在其中放置一些简单的 $log.debug 语句来调试您的客户端,但它似乎不起作用,它对于普通的 Angular 应用程序会有什么影响?也许原因是我不了解 Gulp 的工作原理。以前从未使用过它。听起来您确实有一行代码在此处将授权密钥附加到 HTTP 标头=> github.com/gh0st/ncps-mms/blob/master/client/src/controllers/…
  • 当客户端在需要身份验证时执行 HTTP 调用以命中 API 时,它听起来并没有被客户端使用。您能否尝试将那 1 行(见上文)添加到 $http 用于 GET/POST 需要身份验证的资源的地方?我正在尝试自己做,但不知何故,客户似乎没有接受我的更改。如前所述,这可能只是我缺乏 gulp 知识。让我知道这是否有效。
  • 我已经取得了一些进展,但即使通过身份验证,我的视图仍然无法呈现。请参阅我对 OP 的更新。您可以通过运行npm run watch 来运行应用程序,然后使用npm start 实际启动应用程序。 npm run watch 会将您的最新更改编译到服务器端的任何内容。
  • 尝试执行 npm run watch 但遇到错误。我认为这是我对您正在使用的 babel 东西的有限了解。我在您的项目中提出了一个 github 问题。如果您能帮助我进行设置,将不胜感激。此外,如果您认为您可能已经找到了问题的核心问题,如果您也可以将其标记为已回答,我们将不胜感激!谢谢
猜你喜欢
  • 2018-06-02
  • 2020-08-04
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
相关资源
最近更新 更多