Table of Contents
新浪微博OAuth认证和储存的主要过程详解,oauth详解
Hello <?=$_SESSION['username'] ?>
Home php教程 php手册 新浪微博OAuth认证和储存的主要过程详解,oauth详解

新浪微博OAuth认证和储存的主要过程详解,oauth详解

Jun 13, 2016 am 09:09 AM
oauth oauth authentication store Sina Weibo

新浪微博OAuth认证和储存的主要过程详解,oauth详解

网上很多关于OAuth的文章,但是包括sina本身都都没有详细的的介绍,包括验证过程和验证后数据的储存,所以参考了Twitter的认证过程写下一些详细的注释代码。

在我们开始前,我们先建立一张数据库来保存用户信息,下面是一个基本的 Mysql 的例子:

CREATE TABLE `oauth_users` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `oauth_provider` VARCHAR(10),
  `oauth_uid` text,
  `oauth_token` text,
  `oauth_secret` text,
  `username` text,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Copy after login

注意 oauth_token 和 oauth_secret 这两个字段。sina的 OAuth 认证需要 token 和 token_secret 两个参数来完成认证,所以我们需要预留两个字段来记录他们。

然后我们需要依次完成以下工作:

向 SinaAPI发起认证申请 注册/或者登录,如果用户已经有帐号的情况下 将相关数据保存在 Session 中

基于 OAuth 的认证流程从生成一个网址开始。用户被重定向到该网址要求认证,认证通过后,会重定向到我们的应用服务器,并会将两个认证后的参数通过 URL 方式传回。

建立index.php

<&#63;php
session_start();
//if( isset($_SESSION['last_key']) )
  header("Location: weibolist.php");
include_once( 'config.php' );
include_once( 'weibooauth.php' );
// 创建 sinaOAuth 对象实例
$sinaOAuth = new WeiboOAuth( WB_AKEY , WB_SKEY );
$keys = $sinaOAuth->getRequestToken();
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$aurl = $sinaOAuth->getAuthorizeURL( $keys['oauth_token'] ,false , 'http://t.yourtion.com/sina/callback.php');
// 保存到 session 中
$_SESSION['keys'] = $keys;
&#63;>
<a href="<&#63;=$aurl&#63;>">Use Oauth to login</a>
Copy after login

接下来,我们还需要在这个文件中完成以下三件事:

验证 URL 中的数据
验证 Session 中的 token 数据
验证 Session 中的 secret 数据

如果所有数据库都是合法的,我们需要创建一个新的 SinaOAuth 对象实例,跟之前不同的是,我们要把获取到的 token 数据做为参数传入对象。之后,我们应该可以获取到一个 access token,这个获取到的数据应该是一个数组,这个 access token 是我们唯一需要保存起来的数据。

建立callback.php

<&#63;php
session_start();
include_once ('config.php');
include_once ('weibooauth.php');
if (!empty($_GET['oauth_verifier']) && !empty($_SESSION['keys']['oauth_token']) &&
  !empty($_SESSION['keys']['oauth_token']))
{
  // SinaOAuth 对象实例,注意新加入的两个参数
  $sinaOAuth = new WeiboOAuth(WB_AKEY, WB_SKEY, $_SESSION['keys']['oauth_token'],
    $_SESSION['keys']['oauth_token_secret']);
  // 获取 access token
  $access_token = $sinaOAuth->getAccessToken($_REQUEST['oauth_verifier']);
  // 将获取到的 access token 保存到 Session 中
  $_SESSION['access_token'] = $access_token;
  // 获取用户信息
  $user_info = $sinaOAuth->get('account/verify_credentials');
  // 打印用户信息
  mysql_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PSSWORD);
  mysql_select_db(DATABASE_DB_NAME);
  //更换成你的数据库连接,在config.php中
  if (isset($user_info->error) or empty($user_info['id']))
  {
    // Something's wrong, go back to square 1
    header('Location: index.php');
  } else
  {
    // Let's find the user by its ID
    $sql = "SELECT * FROM oauth_users WHERE oauth_provider='sina' AND oauth_uid=" .$user_info['id'];
    $query = mysql_query($sql);
    $result = mysql_fetch_array($query);
    // If not, let's add it to the database
    if (empty($result))
    {
      $sql = "INSERT INTO oauth_users (oauth_provider, oauth_uid, username, oauth_token, oauth_secret) VALUES ('sina', '" .
        $user_info['id'] . "', '" . $user_info['screen_name'] . "', '" . $access_token['oauth_token'] .
        "', '" . $access_token['oauth_token_secret'] . "')";
      $query = mysql_query($sql);
      $query = mysql_query("SELECT * FROM oauth_users WHERE id = ".mysql_insert_id());
      $result = mysql_fetch_array($query);
    } else
    {
      // Update the tokens
      $query = mysql_query("UPDATE oauth_users SET oauth_token = '" . $access_token['oauth_token'] .
        "', oauth_secret = '" . $access_token['oauth_token_secret'] .
        "' WHERE oauth_provider = 'sina' AND oauth_uid = " . $user_info['id']);
    }
    $_SESSION['id']=$result['id'];
    $_SESSION['username']=$result['username'];
    $_SESSION['oauth_uid']=$result['oauth_uid'];
    $_SESSION['oauth_provider']=$result['oauth_provider'];
    $_SESSION['oauth_token']=$result['oauth_token'];
    $_SESSION['oauth_secret']=$result['oauth_secret'];
    header('Location: update.php');
  }
} else
{
  // 数据不完整,转到上一步
  header('Location: index.php');
}

&#63;>

Copy after login

你可以通过 $user_info->id 来获得用户的 ID,通过 $user_info->screen_name 来获取用户名,等等,其它的信息也可以通过同样的方式获取。

需要重点指出的是,oauth_verifier 这个传回来的参数不能被重用,如果上面的代码已经正确输出了用户信息,你可以试着重新刷新页面,应该会看到页面会抛出一个错误信息,因为 oauth_verifier 已经被我们用过一次了。要再次使用,需要到 index.php 页面重新发起一个认证请求。

用户注册

获得了用户信息后,现在我们要开始把用户信息注册到我们自己的数据库中,当然前提是用户没有在本地数据库注册过。

上面代码中的数据库链接信息要改成你自己的。如果用户已经存在于我们的数据库中,我们需要更新用户的 tokens 字段,因为这说明 Twitter 生成了新的 tokens,数据库中的 tokens 已经过期了。如果用户不存在,我们需要新加一条记录,并将相关的数据保存在 Session中,最后重定向回 update.php 页面。

其中update.php代码如下:

需要注意的是,上面代码中的 SQL 没有经过验证,你在实际使用的时候可能要经过修改。连接数据库前,我们需要先验证一下用户是否已经登录。有了用户名,我们就可以展示一条个性的欢迎信息了:

<&#63;php
include_once ('config.php');
include_once ('weibooauth.php');
session_start();
if(!empty($_SESSION['username'])){
  // User is logged in, redirect
  header('index.php');
}
&#63;>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="zh-CN">
<head profile="http://gmpg.org/xfn/11">
  <title>通过 OAuth 进行身份验证--Yourtion</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
<h2 id="Hello-SESSION-username">Hello <&#63;=$_SESSION['username'] &#63;></h2>
</body>
</html>
Copy after login

这就是OAuth认证和储存的主要过程,希望对你有帮助。 代码下载:SinaOauth

以上就是本文所述的全部内容了,希望大家能够喜欢。

请您花一点时间将文章分享给您的朋友或者留下评论。我们将会由衷感谢您的支持!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP and OAuth: Implementing Microsoft Login Integration PHP and OAuth: Implementing Microsoft Login Integration Jul 28, 2023 pm 05:15 PM

PHP and OAuth: Implementing Microsoft login integration With the development of the Internet, more and more websites and applications need to support users to log in using third-party accounts to provide a convenient registration and login experience. Microsoft account is one of the widely used accounts around the world, and many users want to use Microsoft account to log in to websites and applications. In order to achieve Microsoft login integration, we can use the OAuth (Open Authorization) protocol to achieve it. OAuth is an open-standard authorization protocol that allows users to authorize third-party applications to act on their behalf

OAuth in PHP: Create a JWT authorization server OAuth in PHP: Create a JWT authorization server Jul 28, 2023 pm 05:27 PM

OAuth in PHP: Creating a JWT authorization server With the rise of mobile applications and the trend of separation of front-end and back-end, OAuth has become an indispensable part of modern web applications. OAuth is an authorization protocol that protects users' resources from unauthorized access by providing standardized processes and mechanisms. In this article, we will learn how to create a JWT (JSONWebTokens) based OAuth authorization server using PHP. JWT is a type of

PHP development: Implementing OAuth2 service provider using Laravel Passport PHP development: Implementing OAuth2 service provider using Laravel Passport Jun 15, 2023 pm 04:32 PM

With the popularity of mobile Internet, more and more applications require users to authenticate and authorize themselves. OAuth2 is a popular authentication and authorization framework that provides applications with a standardized mechanism to implement these functions. LaravelPassport is an easy-to-use, secure, and out-of-the-box OAuth2 server implementation that provides PHP developers with powerful tools for building OAuth2 authentication and authorization. This article will introduce the use of LaravelPassport

How to do Google Drive integration using PHP and OAuth How to do Google Drive integration using PHP and OAuth Jul 31, 2023 pm 04:41 PM

How to do GoogleDrive integration using PHP and OAuth GoogleDrive is a popular cloud storage service that allows users to store files in the cloud and share them with other users. Through GoogleDriveAPI, we can use PHP to write code to integrate with GoogleDrive to implement file uploading, downloading, deletion and other operations. To use GoogleDriveAPI we need to authenticate via OAuth and

OAuth2 authentication method and implementation in PHP OAuth2 authentication method and implementation in PHP Aug 07, 2023 pm 10:53 PM

OAuth2 authentication method and implementation in PHP With the development of the Internet, more and more applications need to interact with third-party platforms. In order to protect user privacy and security, many third-party platforms use the OAuth2 protocol to implement user authentication. In this article, we will introduce the OAuth2 authentication method and implementation in PHP, and attach corresponding code examples. OAuth2 is an authorization framework that allows users to authorize third-party applications to access their resources on another service provider without mentioning

How to use Java to develop a single sign-on system based on Spring Security OAuth2 How to use Java to develop a single sign-on system based on Spring Security OAuth2 Sep 20, 2023 pm 01:06 PM

How to use Java to develop a single sign-on system based on SpringSecurityOAuth2 Introduction: With the rapid development of the Internet, more and more websites and applications require users to log in, but users do not want to remember for each website or application. An account number and password. The single sign-on system (SingleSign-On, referred to as SSO) can solve this problem, allowing users to access multiple websites and applications without repeated authentication after logging in once. This article will introduce

Laravel development: How to implement API OAuth2 authentication using Laravel Passport? Laravel development: How to implement API OAuth2 authentication using Laravel Passport? Jun 13, 2023 pm 11:13 PM

As the use of APIs becomes more widespread, protecting the security and scalability of APIs becomes increasingly critical. OAuth2 has become a widely adopted API security protocol that allows applications to access protected resources through authorization. To implement OAuth2 authentication, LaravelPassport provides a simple and flexible way. In this article, we will learn how to implement APIOAuth2 authentication using LaravelPassport. Lar

Using PHP to implement third-party authorization and authentication based on OAuth2 Using PHP to implement third-party authorization and authentication based on OAuth2 Aug 08, 2023 am 10:53 AM

Use PHP to implement third-party authorization and authentication based on OAuth2. OAuth2 is an open standard protocol used to authorize third-party applications to access user resources. It is simple, secure and flexible and is widely used in various web applications and mobile applications. In PHP, we can implement OAuth2 authorization and authentication by using third-party libraries. This article will combine sample code to introduce how to use PHP to implement third-party authorization and authentication based on OAuth2. First, we need to use Compos

See all articles