Home >Backend Development >PHP Tutorial >Detailed explanation of the main processes of Sina Weibo OAuth authentication and storage, oauth detailed explanation_PHP tutorial

Detailed explanation of the main processes of Sina Weibo OAuth authentication and storage, oauth detailed explanation_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-13 10:00:11984browse

Detailed explanation of the main process of OAuth authentication and storage on Sina Weibo, detailed explanation of oauth

There are many articles about OAuth on the Internet, but there is no detailed introduction, including verification, including Sina itself process and storage of data after verification, so I wrote some detailed comment code with reference to Twitter's authentication process.

Before we start, we first create a database to save user information. Here is a basic Mysql example:

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;

Pay attention to the two fields oauth_token and oauth_secret. Sina's OAuth authentication requires two parameters, token and token_secret, to complete the authentication, so we need to reserve two fields to record them.

Then we need to complete the following tasks in order:

Initiate an authentication application to SinaAPI to register/or log in. If the user already has an account, save the relevant data in the Session

The OAuth-based authentication process starts by generating a URL. The user is redirected to this URL to require authentication. After the authentication is passed, the user will be redirected to our application server and the two authenticated parameters will be returned through the URL.

Create 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>

Next, we need to complete the following three things in this file:

Verify data in URL
Verify token data in Session
Verify secret data in Session

If all databases are legal, we need to create a new SinaOAuth object instance. The difference from before is that we need to pass the obtained token data into the object as a parameter. After that, we should be able to obtain an access token. The obtained data should be an array. This access token is the only data we need to save.

Create 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;>

You can get the user ID through $user_info->id, get the user name through $user_info->screen_name, etc. Other information can also be obtained in the same way.

It is important to point out that the parameter returned by oauth_verifier cannot be reused. If the above code has correctly output the user information, you can try to refresh the page, and you should see that the page will throw an error message. Because oauth_verifier has been used by us once. To use it again, you need to go to the index.php page to re-initiate an authentication request.

User Registration

After obtaining the user information, now we need to start registering the user information into our own database. Of course, the premise is that the user has not been registered in the local database.

The database link information in the above code needs to be changed to your own. If the user already exists in our database, we need to update the user's tokens field, because this means Twitter generated new tokens and the tokens in the database have expired. If the user does not exist, we need to add a new record, save the relevant data in the Session, and finally redirect back to the update.php page.

The update.php code is as follows:

It should be noted that the SQL in the above code has not been verified, and you may need to modify it when you actually use it. Before connecting to the database, we need to verify whether the user is logged in. With the username, we can display a personalized welcome message:

<&#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>Hello <&#63;=$_SESSION['username'] &#63;></h2>
</body>
</html>

This is the main process of OAuth authentication and storage. I hope it will be helpful to you. Code download: SinaOauth

That’s all the content of this article, I hope you all like it.

Please take a moment to share the article with your friends or leave a comment. We will sincerely thank you for your support!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/974659.htmlTechArticleDetailed explanation of the main process of OAuth authentication and storage on Sina Weibo, oauth detailed explanation There are many articles about OAuth on the Internet, but including sina There is no detailed introduction itself, including the verification process and verification...
Statement:
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