从 php 中的 google 登录后,如何重定向到最后一个 link?

How to redirect to last link after login from google in php?

我试图在通过 Gmail 或 Facebook 登录后将用户重定向到最后一个 link。

以下是我尝试过但没有成功的四件事。

1) 使用 $_SERVER['HTTP_REFERER'] 但它会将我重定向回 Gmail,而不是我网站上的最后一个 link。

2) 使用 $_SESSION - 我尝试在登录前将最后一个 url 存储在会话中,但登录后我没有得到它的值,因为会话为空。

3) 使用 cookies - 我也尝试使用 cookies 但它也不起作用

4) 我尝试在重定向 url 中将最后一个 url 作为 $_GET 参数发送,但这样做会像 url 那样停止 google 登录与存储在 google 个应用程序中的 url 不匹配。

还有其他方法可以实现吗?

您将使用某些功能检查用户是否已登录,如果没有,您将把用户带到登录页面,用户可以在该页面上使用 Google 或 FB 登录。 假设这样, 我会说,将之前的 link 存储在 SESSION 中,与您检查用户是否登录的功能相同,

我正在编写代码片段,您可以从中获取灵感来编写您的特定代码。

if(isset($_SERVER['HTTP_REFERER']))
{
    $_SESSION['url_to_go'] = $_SERVER['HTTP_REFERER'];
}

当用户成功登录时,检查会话密钥 url_to_go 是否存在,然后将用户重定向到 link 或将他带到仪表板或您拥有的任何默认页面。

因此,正如您所说,当我们从社交网站返回时,会话将被清除,您可以使用 localStorage 和 JS(浏览器存储)来存储 $_SERVER['HTTP_REFERER'],当您返回时,使用一次后可以取回清除。

我不明白为什么使用 cookie 不起作用。在将用户重定向到授权服务器之前,将当前 URL 存储在 cookie 中。当 AS 将用户重定向回 redirect_uri 时,该页面会再次重定向到存储在 cookie 中的 URL。

但我更喜欢在请求中包含“最后一页 URL”(列表中的第 4 个元素)的版本。由于 Google 显然不允许在其 OAuth 配置中使用通配符,因此您可以改用 state 参数。来自 RFC 6749 - The OAuth 2.0 Authorization Framework:

state
     RECOMMENDED.  An opaque value used by the client to maintain
     state between the request and callback.  The authorization
     server includes this value when redirecting the user-agent back
     to the client.  The parameter SHOULD be used for preventing
     cross-site request forgery as described in Section 10.12.

当您构建重定向 URL 时,您只需像这样设置 state 参数:

https://accounts.google.com/o/oauth2/v2/auth
    ?client_id=MY_CLIENT_ID
    &redirect_uri=http://example.com/oauth-redirect_uri
    &scope=REQUESTED_SCOPES
    &state=http://example.com/last-page-the-user-loaded

根据您的 OAuth 流程,授权服务器会将用户重定向到一个 URL,在成功授权后看起来有点像这样:

http://example.com/oauth-redirect_uri
    ?code=CODE
    &state=http://example.com/last-page-the-user-loaded

您的服务器随后可以处理 state 参数并相应地重定向用户。

只需创建一个会话并不断将其值更新为您当前的 url。在 google 登录或注销后,只需重定向到您的会话,该会话将保留您的最后一个 url。

我是用 codeigniter 做的。

//Remember to load 'url' helper to quickly obtain the value of current url
    $data['google_login_url']=$this->google->get_login_url();
    $this->session->set_userdata('last_page', current_url());//This lines creates a session 'last_page' and assigns it a value of the current Url.

登录后

$last_page = $this->session->userdata('last_page');//I obtains the value of last_page
redirect($last_page);

注销后

  $last_page = $this->session->userdata('last_page');
    session_destroy();
    unset($_SESSION['access_token']);
    $session_data=array(
            'sess_logged_in'=>0);
    $this->session->set_userdata($session_data);
    redirect($last_page);