使用 Passport 对 API 端点进行身份验证

2024-03-04

couple https://thinkster.io/mean-stack-tutorial#adding-authentication-via-passport 教程 https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/在使用 jsonwebtoken、护照和护照本地添加身份验证时,我一直坚持将其集成到我的项目 https://github.com/gh0st/ncps-mms。我希望对任何 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');
});

但这似乎也没有达到目的。
我忘记或错过了什么?

EDIT:

输入凭据并单击登录后,我在 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)
    ...

EDIT:

这有很大关系这条线 https://github.com/gh0st/ncps-mms/blob/master/server/routes/member.js#L58当我注入我的服务器路由时auth目的。基本上我认为我的身份验证令牌没有随我的一起发送GET要求。但我认为这就是当我将 auth 对象传递到 GET 请求时发生的情况。

EDIT:

Added image of GET request.
Screenshot of GET request in Chrome.

编辑/更新:

我相信我已经解决了身份验证问题,但我的成员视图状态问题在经过身份验证后仍然无法呈现。我有将我的最新更改推送到 github https://github.com/gh0st/ncps-mms/commit/2569ca0684baa637c1382b22556e585c8b94f6a2如果您提取最新版本并运行,您将看到您可以进行身份​​验证,但单击View链接无法加载视图。


https://github.com/gh0st/ncps-mms https://github.com/gh0st/ncps-mms经过一些修复后,对我来说效果很好......

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

客户端/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.'
    });
});

客户端/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');
        });
    };
}]);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Passport 对 API 端点进行身份验证 的相关文章

随机推荐