简体   繁体   English

使用ajax和php时的用户身份验证和重定向

[英]User authentication and redirect when using ajax and php

I usually restrict user access by redirecting users if they don't have a valid session. 我通常通过重定向用户来限制用户访问,如果他们没有有效的会话。

For example: 例如:

<?php
  session_start();
  if (!isset($_SESSION["userInfo"])) {
    header("Location: index.php");
  }
?>

but I'm starting a new project using ajax for all my page loads. 但我正在使用ajax为我的所有页面加载启动一个新项目。

How should I force a page refresh of my webapp if the session is no longer valid? 如果会话不再有效,我应该如何强制刷新我的webapp?

ShouldIi precede all my ajax request with a dedication authentication request, and if that fails refresh the page via javascript? ShouldIi在我的所有ajax请求之前有一个奉献认证请求,如果失败刷新页面通过javascript?

Or, should I just include authentication data in each of my json responses and then authenticate before any further handling of the ajax requests? 或者,我应该只在每个json响应中包含身份验证数据,然后在进一步处理ajax请求之前进行身份验证吗?

Is there a better way to do this? 有一个更好的方法吗?

Ideally, you engineer your client-side code well enough so you have a way to handle various errors from the server-side. 理想情况下,您可以很好地设计客户端代码,这样您就可以从服务器端处理各种错误。

When your client-side code makes an ajax call, it should look at the status of the response. 当您的客户端代码进行ajax调用时,它应该查看响应的状态。 If the user has no session, the server should reply with 401 (Unauthorized) response, which means "that's a valid URL, but you need to be authenticated". 如果用户没有会话,则服务器应回复401(未授权)响应,这意味着“这是一个有效的URL,但您需要进行身份验证”。

Whenever your client-side code gets a 401, it should do whatever is necessary to get the user logged in. This could be redirecting them to a login screen, or doing some kind of modal authentication DHTML-popup. 每当您的客户端代码获得401时,它应该执行任何必要的操作以使用户登录。这可以将它们重定向到登录屏幕,或者执行某种模式身份验证DHTML-popup。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM