使用 Passport 对 API 端点进行身份验证 [英] Using Passport for Authentication of API Endpoints

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

问题描述

跟随

编辑/更新:

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

解决方案

https://github.com/gh0st/ncps-mms 经过一些修复后对我来说工作正常...

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

client/src/routes.js

/* jshint esversion: 6 *//* jshint 节点:真 */从角度"导入角度;导入角度用户界面路由器";angular.module('ncps.routes', ['ui.router']).config(($stateProvider, $urlRouterProvider) => {$urlRouterProvider.otherwise('/members/login');$stateProvider.state('登录', {url: '/会员/登录',templateUrl: 'members/members-login.html',控制器:'AuthController',onEnter: ['$state', 'auth', function($state, auth) {如果(auth.isLoggedIn()){console.log('去/members/...');$state.go('会员', {//'标题': {//'Authorization': 'Bearer' + auth.getToken()//}});}}]}).state('注册', {url: '/会员/注册',templateUrl: 'members/members-register.html',控制器:'AuthController',onEnter: ['$state', 'auth', function($state, auth) {如果(auth.isLoggedIn()){$state.go('members');}}]}).state('成员', {网址:'/成员',templateUrl: 'members/members-view.html',解决: {成员:函数($http,auth){console.log('正在尝试获取/members....');返回 $http.get('/members', {标题:{授权":承载"+ auth.getToken()}}).then(函数(响应){返回响应.数据;});}},控制器:'MembersController 作为 membersCtrl'}).state('新',{url: '/成员/添加',templateUrl: '/members/members-add.html',控制器:'MembersSaveController 作为 newMemberCtrl'}).state('测试',{url: '/成员/测试',模板:这是一个测试."});});

client/src/controllers/controllers.js

/* jshint esversion: 6 *//* jshint 节点:真 */从角度"导入角度;angular.module('ncps.controllers', []).controller('MembersController', ['$http', 'auth', 'members', function($http, auth, members) {console.log('检索到的成员');this.members = 成员;}]).controller('MembersSaveController', function($stateParams, $state, $http) {this.member = $state.member;this.saveMember = 函数(成员){$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 = 函数(){auth.register($scope.user).error(function(error) {$scope.error = 错误;}).then(函数() {$state.go('members');});};$scope.logIn = 函数() {auth.logIn($scope.user).error(function(error) {$scope.error = 错误;}).then(函数() {$state.go('members');});};$scope.logOut = 函数(){auth.logOut().error(function(error) {$scope.error = 错误;}).then(函数() {$state.go('members');});};}]);

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.

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?

EDIT:

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

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

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)
    ...

EDIT:

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.

EDIT:

Added image of GET request.

EDIT/UPDATE:

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 works fine for me after a few fixes for resolve...

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆