angularjs – NodeJs Passport isAuthenticated()返回false即使在登录后

前端之家收集整理的这篇文章主要介绍了angularjs – NodeJs Passport isAuthenticated()返回false即使在登录后前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是新来的,想要为网站建立本地身份验证.我经历了各种来源,这个 https://vickev.com/#!/article/authentication-in-single-page-applications-node-js-passportjs-angularjs是非常有帮助的.当我尝试在本地主机中构建相同的代码时,我的代码进入了一个循环.

app.post(‘/ login’,…..)在响应中返回用户,但在加载管理页面之后,它将检查用户是否通过调用app.get(‘/ loggedin’)登录. ..)和req.isAuthenticated()即使在登录后也返回false,它进入一个循环.我不明白为什么这是发生在帮助我.

服务器端代码

  1. var express = require('express');
  2. var http = require('http');
  3. var path = require('path');
  4. var passport = require('passport');
  5. var LocalStrategy = require('passport-local').Strategy;
  6.  
  7. //==================================================================
  8. // Define the strategy to be used by PassportJS
  9. passport.use(new LocalStrategy(
  10. function(username,password,done) {
  11. if (username === "admin" && password === "admin") // stupid example
  12. return done(null,{name: "admin"});
  13.  
  14. return done(null,false,{ message: 'Incorrect username.' });
  15. }
  16. ));
  17.  
  18. // Serialized and deserialized methods when got from session
  19. passport.serializeUser(function(user,done) {
  20. done(null,user);
  21. });
  22.  
  23. passport.deserializeUser(function(user,user);
  24. });
  25.  
  26. // Define a middleware function to be used for every secured routes
  27. var auth = function(req,res,next){
  28. if (!req.isAuthenticated())
  29. res.send(401);
  30. else
  31. next();
  32. };
  33. //==================================================================
  34.  
  35. // Start express application
  36. var app = express();
  37.  
  38. // all environments
  39. app.set('port',process.env.PORT || 3000);
  40. app.use(express.favicon());
  41. app.use(express.cookieParser());
  42. app.use(express.bodyParser());
  43. app.use(express.methodOverride());
  44. app.use(express.session({ secret: 'securedsession' }));
  45. app.use(passport.initialize()); // Add passport initialization
  46. app.use(passport.session()); // Add passport initialization
  47. app.use(app.router);
  48.  
  49. app.all('*',function(req,next) {
  50. res.header("Access-Control-Allow-Origin","*");
  51. res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");
  52. next();
  53. });
  54.  
  55. // development only
  56. if ('development' == app.get('env')) {
  57. app.use(express.errorHandler());
  58. }
  59.  
  60. //==================================================================
  61. // routes
  62. app.get('/',res){
  63. res.render('index',{ title: 'Express' });
  64. });
  65.  
  66. app.get('/users',auth,res){
  67. res.send([{name: "user1"},{name: "user2"}]);
  68. });
  69. //==================================================================
  70.  
  71. //==================================================================
  72. // route to test if the user is logged in or not
  73. app.get('/loggedin',res) {
  74. res.send(req.isAuthenticated() ? req.user : '0');
  75. });
  76.  
  77. // route to log in
  78. app.post('/login',passport.authenticate('local'),res) {
  79. res.send(req.user);
  80. });
  81.  
  82. // route to log out
  83. app.post('/logout',res){
  84. req.logout();
  85. res.send(200);
  86. });
  87. //==================================================================
  88.  
  89. http.createServer(app).listen(app.get('port'),function(){
  90. console.log('Express server listening on port ' + app.get('port'));
  91. });

客户端Js文件

  1. 'use strict';
  2.  
  3. /**********************************************************************
  4. * Angular Application
  5. **********************************************************************/
  6. var app = angular.module('app',['ngResource','ngRoute'])
  7. .config(function($routeProvider,$locationProvider,$httpProvider) {
  8. //================================================
  9. // Check if the user is connected
  10. //================================================
  11. var checkLoggedin = function($q,$timeout,$http,$location,$rootScope){
  12. // Initialize a new promise
  13. var deferred = $q.defer();
  14.  
  15. // Make an AJAX call to check if the user is logged in
  16. $http.get('http://localhost:3000/loggedin').success(function(user){
  17. // Authenticated
  18. if (user !== '0')
  19. $timeout(deferred.resolve,0);
  20.  
  21. // Not Authenticated
  22. else {
  23. $rootScope.message = 'You need to log in.';
  24. $timeout(function(){deferred.reject();},0);
  25. $location.url('/login');
  26. }
  27. });
  28.  
  29. return deferred.promise;
  30. };
  31. //================================================
  32.  
  33. //================================================
  34. // Add an interceptor for AJAX errors
  35. //================================================
  36. $httpProvider.responseInterceptors.push(function($q,$location) {
  37. return function(promise) {
  38. return promise.then(
  39. // Success: just return the response
  40. function(response){
  41. return response;
  42. },// Error: check the error status to get only the 401
  43. function(response) {
  44. if (response.status === 401)
  45. $location.url('/login');
  46. return $q.reject(response);
  47. }
  48. );
  49. }
  50. });
  51. //================================================
  52.  
  53. //================================================
  54. // Define all the routes
  55. //================================================
  56. $routeProvider
  57. .when('/',{
  58. templateUrl: 'views/main.html'
  59. })
  60. .when('/admin',{
  61. templateUrl: 'views/admin.html',controller: 'AdminCtrl',resolve: {
  62. loggedin: checkLoggedin
  63. }
  64. })
  65. .when('/login',{
  66. templateUrl: 'views/login.html',controller: 'LoginCtrl'
  67. })
  68. .otherwise({
  69. redirectTo: '/login'
  70. });
  71. //================================================
  72.  
  73. }) // end of config()
  74. .run(function($rootScope,$http){
  75. $rootScope.message = '';
  76.  
  77. // logout function is available in any pages
  78. $rootScope.logout = function(){
  79. $rootScope.message = 'Logged out.';
  80. $http.post('http://localhost:3000/logout');
  81. };
  82. });
  83.  
  84.  
  85. /**********************************************************************
  86. * Login controller
  87. **********************************************************************/
  88. app.controller('LoginCtrl',function($scope,$rootScope,$location) {
  89. // This object will be filled by the form
  90. $scope.user = {};
  91.  
  92. // Register the login() function
  93. $scope.login = function(){
  94. $http.post('http://localhost:3000/login',{
  95. username: $scope.user.username,password: $scope.user.password,})
  96. .success(function(user){
  97. // No error: authentication OK
  98. $rootScope.message = 'Authentication successful!';
  99. $location.url('/admin');
  100. })
  101. .error(function(){
  102. // Error: authentication Failed
  103. $rootScope.message = 'Authentication Failed.';
  104. $location.url('/login');
  105. });
  106. };
  107. });
  108.  
  109.  
  110.  
  111. /**********************************************************************
  112. * Admin controller
  113. **********************************************************************/
  114. app.controller('AdminCtrl',$http) {
  115. // List of users got from the server
  116. $scope.users = [];
  117.  
  118. // Fill the array to display it in the page
  119. $http.get('http://localhost:3000/users').success(function(users){
  120. for (var i in users)
  121. $scope.users.push(users[i]);
  122. });
  123. });
您需要允许将Cookie设置为跨域

在快递

  1. res.header('Access-Control-Allow-Credentials',true);

并在ajax设置

  1. xhrFields: {
  2. withCredentials: true
  3. }

您可以找到相关的答案herehere

猜你在找的Angularjs相关文章