【问题标题】:if not authorized after Google OAuth, redirect to specific page如果在 Google OAuth 之后未授权,则重定向到特定页面
【发布时间】:2019-06-09 23:47:20
【问题描述】:

我让 Google 登录正常工作,但不知道如何只允许我的数据库中已有的用户。我试图只允许其 Google 电子邮件位于 MyTable 表的 Mail 列中的用户。如果用户不在表中,则重定向到unauthorized.html。现在,如果我不检查数据库,登录工作正常。

我认为我有两个概念问题:

1) 不知道重定向是在data-redirecturi="http://MyPage.php" 还是window.location.replace("http://MyPage.php");

2) 如果用户的电子邮件不在数据库中,我不知道如何重定向到 unauthorized.html

html:

<div class="WelcomeContainer">
  <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark" data-redirecturi="http://MyPage.php"></div>
</div>
<script>
function onSignIn(googleUser) {
  var id_token = googleUser.getAuthResponse().id_token;
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'signin.php');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onload = function() {
      window.location.replace("http://MyPage.php");
  };
  xhr.send('idtoken=' + id_token);      
}
</script>

signin.php:

<?php
session_start();
require_once 'vendor/autoload.php';
$CLIENT_ID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
$id_token = $_POST['idtoken'];
$client = new Google_Client(['client_id' => $CLIENT_ID]);
$payload = $client->verifyIdToken($id_token);
if ($payload) {
    $link = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

    $Test=false;
    $result = $link->query("SELECT Mail FROM  MyTable");
    while ($row = $result->fetch_assoc()) {
        if ($row['Mail']==$payload['email']) {
            $Test=true;
        }
    }

    if ($Test==true) {
        //code here for success?
    }
    else {
        //code here for failure?
    }  
} else {
    die();
}
?>

【问题讨论】:

  • 对不起,我错过了 XHR 部分,所以我删除了我的答案。您将需要返回错误unauthorized 并让您的代码在客户端运行以处理错误。
  • 看看这个 SO 答案:stackoverflow.com/a/8866912/8016720
  • 谢谢!您的指导方针帮助我解决了这个问题(尽管我不知道解决方案是否优雅)。我将在几分钟内发布代码。

标签: php google-oauth


【解决方案1】:

以下代码似乎有效。

在 html 中我替换了这个:

xhr.onload = function() {
    window.location.replace("http://MyPage.php");
};

用这个:

xhr.onload = function() {
    if (xhr.readyState == 4 && xhr.status==200) {
        window.location.replace(xhr.responseText);
    }
};

在signin.php中

if ($Test==true) {
  echo "http://www.example.com/TheGoodPage.html";
}
else {
  echo "http://www.example.com/TheUnAuthorizedPage.html";
}    

【讨论】:

  • 我看到的唯一直接问题是返回 url。 http://TheUnAuthorizedPage.html 不起作用。使用完整的 URL。此外,如果您计划支持 HTTPS,那么现在在您的代码中处理它。
  • 已编辑。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 2015-10-27
  • 2015-11-26
  • 1970-01-01
  • 2012-03-13
  • 2011-11-18
  • 1970-01-01
相关资源
最近更新 更多