简体   繁体   中英

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.

How should I force a page refresh of my webapp if the session is no longer valid?

ShouldIi precede all my ajax request with a dedication authentication request, and if that fails refresh the page via 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?

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. 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".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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