- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我需要处理 Angular 上的持久 session 应用程序使用 express和 passport在后端。成功登录后,如果我对返回 request.isAuthenticated() 的 Express API 进行 http 调用(使用 Angular $http ),它总是返回 false。当我登录并使用 Postman 对 API 进行 http 调用时,情况并非如此,在这种情况下我得到了 true。
这是我在服务器上的配置:
服务器.js
const
express = require('express'),
config = require("../config"),
path = require('path'),
bodyParser = require('body-parser'),
cookiePraser = require('cookie-parser'),
cors = require('cors'),
winston = require("winston"),
morgan = require("morgan"),
mongoose = require("mongoose"),
passport = require("passport"),
session = require("express-session"),
flash = require("connect-flash"),
let app = express(),
server = require("http").Server(app),
io = require("socket.io")(server);
const sessionKey = "mySessionKey";
/*
* ---------------------------------------------------------------------------------------
* app configuration
* ---------------------------------------------------------------------------------------
*/
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.use(morgan("dev"));
app.use(bodyParser.json({limit: "50mb"}));
app.use(cookiePraser(sessionKey));
app.use(express.static("public"));
app.use(session({
secret: sessionKey,
resave: true,
saveUninitialized: true,
cookie: {
secure: false,
httpOnly: false
}
}));
app.use(passport.initialize());
app.use(passport.session());
require("./passportConfig")(passport); // passport configuration
app.get("api/test", function(req, res){
return json({isAuthenticated: req.isAuthenticated()});
})
// [..]
passportConfig.js
const LocalStrategy = require("passport-local").Strategy,
User = require("./models/User");
module.exports = function(passport) {
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function () {
User.findOne({'local.email': email}, function (err, user) {
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// if there is no user with that email
// create the user
let newUser = new User();
// set the user's local credentials
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
// save the user
newUser.save(function (err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}
));
passport.use('local-login', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, user);
});
}
));
};
loginService.js(公开登录函数):
this.login = function(email, password) {
return new Promise((resolve, reject) => {
$http({
url: serverBaseURL + "/api/login",
method: "POST",
`enter code here` data: JSON.stringify({
email: email,
password: password
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
}).then(function (response) {
resolve(response);
}, function (errorResponse) {
reject(errorResponse);
});
});
};
在 Controller 中,我执行登录,然后进行另一个 http 调用来检查我是否确实登录:
登录Ctrl.js
loginService.login($scope.email, $scope.password).then(response => {
if (response.status === 200) {
// check if I am really logged in, include the connect.sid cookie in the call => withCredentials = true
$http({
url: serverBaseURL + "/api/test",
method: "GET",
headers: {
"Accept": "application/json"
},
withCredentials: true,
}).then(function (response) {
console.log(response); // I always get false in the response
}, function (errorResponse) {
console.log(errorResponse);
});
}
}, error => {
// handle error
});
// [..]
我注意到两件事:
知道我错过了什么吗?
最佳答案
我发现这个问题是因为我有同样的情况,从 request.isAuthenticated() 和状态 401 总是得到错误。解决方案正如 @Mukesh Sharma 所写,不要忘记在客户端前端添加:
{ withCredentials: true }
关于node.js - 快速 session 和 Passport : req. isAuthenticated() 登录后返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44510063/
在 MVC4 应用程序中,在 Controller 逻辑中我想检查用户是否已登录。 我应该使用: User.Identity.IsAuthenticated 或者: WebSecurity.IsAut
我有一个 IsAuthenticated 方法,它有一个复杂的参数类型(我从 play2 的 zentasks 示例中复制了它): def IsAuthenticated(f: => String =
用户提交登录 POST 数据。 Passport.js 进行身份验证。 req.isAuthenticated() 为 true。 将用户从登录路径重定向至主页 在主页路由中,req.isAuthen
我开始学习node/express js,并且我使用passport制作了一个登录系统,但是我想在我的系统中制作一个成员(member)页面只能供已经登录的用户,经过一番研究我找到了答案here ,并
我开始学习node/express js,并且我使用passport制作了一个登录系统,但是我想在我的系统中制作一个成员(member)页面只能供已经登录的用户,经过一番研究我找到了答案here ,并
我正在使用 MVC 格式创建网站。现在它所做的只是从 SQL 服务器管理用户。我现在要做的是让用户登录,然后能够管理用户。它应该从登录页面转到帐户索引,但我只希望经过身份验证的用户可以查看此页面。它工
我正在尝试修复以下错误: /home/ubuntu/workspace/src/util/utils.js:2 if (req.isAuthenticated()) { ^ T
我已经实现了passport.js,登录时我将passport.authenticated()函数放在中间件中。 app.post('/api/v1/login', function
server.ext('onRequest', (request, reply) => { request.context = { token: request.headers['X-AC
这可能是个愚蠢的问题,但我在 Google 上搜索得很辛苦,却找不到答案。 我正在创建一个数据库位于另一个大陆的网站,因此速度是一个至关重要的问题。 据我了解, WebSecurity.Login(
我有一个关于 ASP.NET 身份提供程序的问题。我做了一个系统,你可以在其中对用户和角色执行 CRUD 操作,尽管我遇到了一个问题。如果我要删除一个已经通过身份验证(登录)的用户,他仍然可以在网站上
MSDN 代码示例说明:以下代码示例使用 IsAuthenticated 属性来确定当前请求是否已通过身份验证。如果尚未通过身份验证,请求将被重定向到另一个页面,用户可以在该页面中将其凭据输入到 We
我有一个 HttpModule实现了应该限制对 /courses/ 的访问我网站的目录,但有一个主要问题。 Request.IsAuthenticated总是 false . 这是代码: using
我的 Express 应用程序调用 request.isAuthenticated() 方法。但是,我不知道它检查什么来确定它是否经过身份验证。我的应用需要通过 OIDC 进行身份验证。如何告诉 is
我试图在我的 Controller 中调用 isAuthenticated 方法,但它告诉我不是一个函数。下面是我的代码片段。 Controller (function() { 'use strict
当我登录时,我已通过身份验证,但当我切换到另一个页面时,req.isAuthenticated 返回 false,并且我位于登录面板上。第二件事是,当我登录时,我不断收到错误“发送后无法设置 head
我使用 passportjs 的身份验证功能将始终返回 false,即使用户已经存在,它也将始终重定向到登录页面,这会覆盖我所有的身份验证路由,因此当我使用有效的用户凭据登录或创建新的用户,默认行为是
我已经寻找了一段时间,但找不到明确的文档来源。当我搜索这些内容时,第一个 Google 结果是 StackOverflow。 还有类似的中间件功能吗? 最佳答案 虽然在任何容易找到的地方都没有明确记录
我想为 Play2 Framework 应用创建自定义身份验证方法。我正在 Scala 和 Play 中尝试——而且我对这两者都是新手。 在 zentask 示例中,Trait Secured 中有一
我使用 passportjs 的身份验证功能将始终返回 false,即使用户已经存在,它也将始终重定向到登录页面,这会覆盖我所有的身份验证路由,因此当我使用有效的用户凭据登录或创建新的用户,默认行为是
我是一名优秀的程序员,十分优秀!