


Detailed explanation of the main processes of Sina Weibo OAuth authentication and storage, oauth detailed explanation_PHP tutorial
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
<?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; ?> <a href="<?=$aurl?>">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
<?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'); } ?>
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:
<?php include_once ('config.php'); include_once ('weibooauth.php'); session_start(); if(!empty($_SESSION['username'])){ // User is logged in, redirect header('index.php'); } ?> <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 <?=$_SESSION['username'] ?></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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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

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

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 create a group chat on Sina Weibo app? Sina Weibo app is a software that allows users to socialize on this software. Users can follow each other here and send private messages to other users here. In other words, users can socialize on this software. Chat. In addition, this software also allows users to create group chats and then chat. Many users still don’t know how to create a group chat. The editor below has compiled methods for creating group chats for your reference. How to create a group chat on Sina Weibo app 1. First, open the software, find and click the "Gear" option in the upper right corner of the "Message" interface; 2. Then, click on the pop-up option box

Introduction to how to use PHP and OAuth for QQ login integration: With the development of social media, more and more websites and applications are beginning to provide third-party login functions to facilitate users to quickly register and log in. As one of China's largest social media platforms, QQ has also become a third-party login service provided by many websites and applications. This article will introduce the steps on how to use PHP and OAuth for QQ login integration, with code examples. Step 1: Register as a QQ open platform developer. Before starting to integrate QQ login, I
