本文介绍了使用Passport进行API端点身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循夫妇 教程有关使用jsonwebtoken,护照和护照添加身份验证-local我一直坚持将其集成到我的项目中.我想要这样,以便对任何API端点的任何请求都需要身份验证,并且对触及该API的前端的任何请求都需要身份验证.

Following a couple tutorials on adding authentication using jsonwebtoken, passport, and passport-local I've become stuck on integrating it into my project. I want it so that any requests to any of the API endpoints require authentication, and also any requests to the front end which touch the API require authentication.

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

What is happening now is I can get a user to log in and register but once they are logged in they are still unable to visit a page which is requiring authentication. The user gets a 401 error. It's like the token isn't being passed correctly in the request.

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

I tried adding an 'auth interceptor' too

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

但是这似乎也没有解决问题的方法.
我忘记或丢失了什么?

But this didn't seem to do the trick either.
What am I forgetting or missing?

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

After entering creds and clicking log in I get this error in chrome console

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

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

But my nav links show up as they're supposed to after I've successfully authenticated.
I also get this error in my terminal where I'm running Node

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

这与当我注入auth对象时,服务器路由的这一行.基本上,我认为我的身份验证令牌未随我的GET请求发送.但是我认为当我将auth对象传递给GET请求时,就会发生这种情况.

It has a lot to do with this line of my server routes when I inject my auth object. Basically I think my auth token isn't getting sent with my GET request. But I thought that this is what happens when I pass my auth object into the GET request.

添加了GET请求的图片.

Added image of GET request.

我相信我已经走过了我的身份验证问题,但是成员视图状态的问题在经过身份验证后仍然无法呈现.我已经将我对github的最新更改,如果您拉最新的和运行后,您会看到可以进行身份​​验证,但是单击 View 链接无法加载视图.

I believe I've made my way past my authentication problem but the issue of my members-view state continues to fail to render after authenticated. I've pushed my latest changes to github and if you pull the latest and run you will see that you can authenticate but clicking the View link fails to load the view.

推荐答案

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

https://github.com/gh0st/ncps-mms works fine for me after a few fixes for resolve...

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

client/src/routes.js

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

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

这篇关于使用Passport进行API端点身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 01:27