Jor*_*nda 3 javascript ajax node.js express passport.js
我在使用Passport时遇到了一个问题:在调用我的自定义端点时,我无法检查用户是否经过身份验证.
我已按以下方式配置了Express4应用程序:
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// required for passport
app.use(session({ secret: 'secretphrase' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(checkAuth); // CHECK SESSION
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(prepareRequests);
Run Code Online (Sandbox Code Playgroud)
checkAuth()中间件具有以下代码:
var checkAuth = function(request, response, next) {
console.log("------------");
console.log("checkAuth user: " + request.session.passport.user);
console.log("checkAuth isAuthenticated: " + request.isAuthenticated());
next();
}
Run Code Online (Sandbox Code Playgroud)
我第一次尝试使用护照登录时,isAuthenticated是假的.一旦我登录,每次打电话给我的服务器,当我的中间件通过时,被认证是假的!!! 但是,奇怪的是,如果我再次尝试登录,则isAuthenticated是真的.
这意味着只有我的AJAX调用返回isAuthenticated = false,但是当我maka表单帖子或点击指向API的链接时,它返回true!然后存储会话,但不存储AJAX请求.
我做错了什么?饼干没有通过吗?
似乎与Dropped.on.Caprica交谈有助于我找到解决方案....
服务器已登录并成功保存会话.但是,您必须在以下AJAX请求中传递Express创建的cookie(withCredentials = true).如果您使用JQuery,请按以下方式:
$.ajax({
url: 'http://127.0.0.1:3003/users/me',
type: 'GET',
xhrFields: {
withCredentials: true
}}).done(function() {
alert( "done" );
});
Run Code Online (Sandbox Code Playgroud)
如果你不是:
var request = window.XDomainRequest ? new XDomainRequest() : new XMLHttpRequest();
var pda;
request.withCredentials = true;
Run Code Online (Sandbox Code Playgroud)
然后,在每次调用时,在Node.JS服务器中,请求request.isAuthenticated()将返回正确的值!
其他提示:不要忘记在Express响应中修改响应标头以允许凭据并指定源以使其在Chrome中运行:
response.header("Access-Control-Allow-Credentials", "true");
response.header("Access-Control-Allow-Origin", "http://127.0.0.1:3008");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1906 次 |
| 最近记录: |