即使登录后护照的NodeJS isAuthenticated()返回false [英] NodeJs Passport isAuthenticated() returning false even after login
问题描述
我是新来angularJs并试图建立本地认证的网站。我已经通过各种渠道消失,这<一个href=\"https://vickev.com/#!/article/authentication-in-single-page-applications-node-js-passportjs-angularjs\">https://vickev.com/#!/article/authentication-in-single-page-applications-node-js-passportjs-angularjs是非常有益的。当我试图建立我的本地同我的code进去一个循环。
app.post('/登录',......)在响应返回用户,但之后加载它正在检查用户是否通过调用app.get记录在管理页面('/的loggedIn ',...)和req.isAuthenticated()即使在登录后返回假,它进入一个循环。我不明白为什么会这样plz帮助我。
服务器端code
VAR前preSS =要求('前preSS');
VAR HTTP =要求('HTTP');
VAR路径=要求('路径');
VAR护照=要求('护照');
VAR LocalStrategy =要求('护照本地')战略。// ================================================ ==================
//定义由PassportJS使用的策略
passport.use(新LocalStrategy(
功能(用户名,密码,完成){
如果(用户名===管理员和放大器;&放大器;密码===管理员)//愚蠢的例子
返回完成(NULL,{名字:管理员}); 返回DONE(空,假,{消息:不正确的用户名。'});
}
));//序列化和会话时得到了反序列化方法
passport.serializeUser(功能(用户,完成){
DONE(NULL,用户);
});passport.deserializeUser(功能(用户,完成){
DONE(NULL,用户);
});//定义一个中间件功能要用于每担保路由
VAR AUTH =功能(REQ,资源,下一个){
如果(!req.isAuthenticated())
res.send(401);
其他
下一个();
};
// ================================================ ==================//开始前preSS应用
VAR应用=前preSS();//所有环境
app.set('口',process.env.PORT || 3000);
app.use(如press.favicon());
app.use(如press.cookieParser());
app.use(如press.bodyParser());
app.use(如press.methodOverride());
app.use(如press.session({秘密:securedsession'}));
app.use(passport.initialize()); //添加初始化护照
app.use(passport.session()); //添加初始化护照
app.use(app.router);app.all('*',函数(REQ,资源,下一个){
res.header(访问控制允许原产地,*);
res.header(访问控制允许报头,原产地,X-要求-着,内容类型,接受);
下一个();
});只有//发展
如果('发展'== app.get('ENV')){
app.use(如press.errorHandler());
}// ================================================ ==================
//路线
app.get('/',函数(REQ,RES){
res.render('指数',{标题:前preSS'});
});app.get('/用户,权威性,功能(REQ,RES){
res.send([{名:USER1},{名字:用户2}]);
});
// ================================================ ==================// ================================================ ==================
//路线测试,如果用户登录或不
app.get('/的loggedIn'功能(REQ,RES){
res.send(?req.isAuthenticated()req.user:0);
});//航线登录
app.post('/登录,passport.authenticate(本地),功能(REQ,RES){
res.send(req.user);
});//路线注销
app.post('/注销,功能(REQ,RES){
req.logOut();
res.send(200);
});
// ================================================ ==================http.createServer(APP)。听(app.get('端口'),功能(){
的console.log('前preSS服务器侦听端口+ app.get('端口'));
});
客户端的js文件
使用严格的;/ ******************* *********************
*角应用
************************************************** ********** /
VAR应用= angular.module('应用',['ngResource','ngRoute'])
的.config(函数($ routeProvider,$ locationProvider,$ httpProvider){
// ================================================
//检查用户连接
// ================================================
VAR checkLoggedin =功能($ Q $超时,$ HTTP,$位置$ rootScope){
//初始化新承诺
变种推迟= $ q.defer(); //使AJAX调用来检查用户登录
$ http.get(的http://本地主机:3000 /的loggedIn').success(功能(用户){
//验证的
如果(用户!=='0')
$超时(deferred.resolve,0); //未通过身份验证
其他{
$ rootScope.message ='您需要登录';
$超时(函数(){deferred.reject();},0);
$ location.url('/登录');
}
}); 返回deferred.promise;
};
// ================================================ // ================================================
//添加AJAX错误拦截
// ================================================
$ httpProvider.responseInterceptors.push(函数($ Q $位置){
复位功能(承诺){
返回promise.then(
//成功:刚刚返回响应
功能(响应){
返回响应;
},
//错误:检查错误状态,只得到401
功能(响应){
如果(response.status === 401)
$ location.url('/登录');
返回$ q.reject(响应);
}
);
}
});
// ================================================ // ================================================
//定义所有路由
// ================================================
$ routeProvider
。什么时候('/', {
templateUrl:意见/ main.html中
})
。当('/管理员',{
templateUrl:意见/ admin.html',
控制器:'AdminCtrl',
解析:{
的loggedIn:checkLoggedin
}
})
。当('/登录',{
templateUrl:意见/ login.html的,
控制器:'LoginCtrl
})
。除此以外({
redirectTo:/登录
});
// ================================================ })//配置的结束()
.RUN(函数($ rootScope,$ HTTP){
$ rootScope.message =''; //注销功能在任何页面可用
$ rootScope.logout =功能(){
$ rootScope.message ='登出。;
$ http.post(的http://本地主机:3000 /注销');
};
});
/ ******************* *********************
*登录控制器
************************************************** ********** /
app.controller('LoginCtrl',函数($范围,$ rootScope,$ HTTP,$位置){
//该目的将通过的形式来填充
$ scope.user = {}; //注册登录()函数
$ scope.login =功能(){
$ http.post(的http://本地主机:3000 /登录',{
用户名:$ scope.user.username,
密码:$ scope.user.password,
})
.success(功能(用户){
//没有错误:验证OK
$ rootScope.message =身份验证成功!;
$ location.url('/管理员');
})
.error(函数(){
//错误:身份验证失败
$ rootScope.message ='验证失败。;
$ location.url('/登录');
});
};
});/ ******************* *********************
*管理控制器
************************************************** ********** /
app.controller('AdminCtrl',函数($范围,$ HTTP){
//用户列表从服务器得到
$ scope.users = []; //填充阵列中的页面来显示它
$ http.get(的http://本地主机:3000 /用户).success(功能(用户){
对(在用户变种I)
$ scope.users.push(网友[我]);
});
});
您需要允许Cookie在跨站点设置
在EX preSS
res.header(访问控制允许的凭据',真);
和阿贾克斯设置
xhrFields:{
withCredentials:真
}
您可以找到相关的答案<一个href=\"http://stackoverflow.com/questions/24687313/what-exactly-does-the-access-control-allow-credentials-header-do\">here和<一个href=\"http://stackoverflow.com/questions/25732131/passport-ex$p$pss4-not-getting-authenticated-when-using-ajax\">here
I'm new to angularJs and trying to build local authentication for a website. I have gone through various sources and this https://vickev.com/#!/article/authentication-in-single-page-applications-node-js-passportjs-angularjs was very helpful. When i tried build the same in my localhost my code went in to a loop.
app.post('/login',.....) is returning user in the response but after that while loading the admin page it is checking whether the user is logged in by calling app.get('/loggedin',... ) and req.isAuthenticated() is returning false even after login and it goes to a loop. i can't understand why this is happening plz help me.
Server Side code
var express = require('express');
var http = require('http');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
//==================================================================
// Define the strategy to be used by PassportJS
passport.use(new LocalStrategy(
function(username, password, done) {
if (username === "admin" && password === "admin") // stupid example
return done(null, {name: "admin"});
return done(null, false, { message: 'Incorrect username.' });
}
));
// Serialized and deserialized methods when got from session
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
// Define a middleware function to be used for every secured routes
var auth = function(req, res, next){
if (!req.isAuthenticated())
res.send(401);
else
next();
};
//==================================================================
// Start express application
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'securedsession' }));
app.use(passport.initialize()); // Add passport initialization
app.use(passport.session()); // Add passport initialization
app.use(app.router);
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
//==================================================================
// routes
app.get('/', function(req, res){
res.render('index', { title: 'Express' });
});
app.get('/users', auth, function(req, res){
res.send([{name: "user1"}, {name: "user2"}]);
});
//==================================================================
//==================================================================
// route to test if the user is logged in or not
app.get('/loggedin', function(req, res) {
res.send(req.isAuthenticated() ? req.user : '0');
});
// route to log in
app.post('/login', passport.authenticate('local'), function(req, res) {
res.send(req.user);
});
// route to log out
app.post('/logout', function(req, res){
req.logOut();
res.send(200);
});
//==================================================================
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Client Side Js file
'use strict';
/**********************************************************************
* Angular Application
**********************************************************************/
var app = angular.module('app', ['ngResource','ngRoute'])
.config(function($routeProvider, $locationProvider, $httpProvider) {
//================================================
// Check if the user is connected
//================================================
var checkLoggedin = function($q, $timeout, $http, $location, $rootScope){
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('http://localhost:3000/loggedin').success(function(user){
// Authenticated
if (user !== '0')
$timeout(deferred.resolve, 0);
// Not Authenticated
else {
$rootScope.message = 'You need to log in.';
$timeout(function(){deferred.reject();}, 0);
$location.url('/login');
}
});
return deferred.promise;
};
//================================================
//================================================
// Add an interceptor for AJAX errors
//================================================
$httpProvider.responseInterceptors.push(function($q, $location) {
return function(promise) {
return promise.then(
// Success: just return the response
function(response){
return response;
},
// Error: check the error status to get only the 401
function(response) {
if (response.status === 401)
$location.url('/login');
return $q.reject(response);
}
);
}
});
//================================================
//================================================
// Define all the routes
//================================================
$routeProvider
.when('/', {
templateUrl: 'views/main.html'
})
.when('/admin', {
templateUrl: 'views/admin.html',
controller: 'AdminCtrl',
resolve: {
loggedin: checkLoggedin
}
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
.otherwise({
redirectTo: '/login'
});
//================================================
}) // end of config()
.run(function($rootScope, $http){
$rootScope.message = '';
// Logout function is available in any pages
$rootScope.logout = function(){
$rootScope.message = 'Logged out.';
$http.post('http://localhost:3000/logout');
};
});
/**********************************************************************
* Login controller
**********************************************************************/
app.controller('LoginCtrl', function($scope, $rootScope, $http, $location) {
// This object will be filled by the form
$scope.user = {};
// Register the login() function
$scope.login = function(){
$http.post('http://localhost:3000/login', {
username: $scope.user.username,
password: $scope.user.password,
})
.success(function(user){
// No error: authentication OK
$rootScope.message = 'Authentication successful!';
$location.url('/admin');
})
.error(function(){
// Error: authentication failed
$rootScope.message = 'Authentication failed.';
$location.url('/login');
});
};
});
/**********************************************************************
* Admin controller
**********************************************************************/
app.controller('AdminCtrl', function($scope, $http) {
// List of users got from the server
$scope.users = [];
// Fill the array to display it in the page
$http.get('http://localhost:3000/users').success(function(users){
for (var i in users)
$scope.users.push(users[i]);
});
});
You need to allow cookies to be set in cross domain
In express
res.header('Access-Control-Allow-Credentials', true);
And in ajax setup
xhrFields: {
withCredentials: true
}
You can find relevant answers here and here
这篇关于即使登录后护照的NodeJS isAuthenticated()返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!