Details on the OAuth authentication and Storage Processes on Sina Weibo and oauth

Source: Internet
Author: User
Tags oauth

Details on the OAuth authentication and Storage Processes on Sina Weibo and oauth

There are a lot of articles on OAuth on the Internet, but sina itself is not described in detail, including the verification process and storage of verified data, therefore, I wrote some detailed comments to the Twitter authentication process.

Before we start, we first create a database to save user information. Below 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;

Note the oauth_token and oauth_secret fields. The OAuth authentication of sina requires the token and token_secret parameters to complete the authentication. Therefore, we need to reserve two fields to record them.

Then we need to complete the following tasks in sequence:

Initiate an authentication request to SinaAPI for registration/or logon. If the user already has an account, save the relevant data in the Session.

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

Create index. php

<? Phpsession_start (); // if (isset ($ _ SESSION ['last _ key']) header ("Location: weibolist. php "); include_once ('config. php '); include_once ('weibooauth. php '); // create a sinaOAuth object instance $ 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 ['oss _ token' ], False, 'HTTP: // t.yourtion.com/sina/callback.php'); // save it to the session $ _ SESSION ['keys '] = $ keys;?> <A href = "<? = $ Aurl?> "> Use Oauth to login </a>

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

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

If all databases are valid, we need to create a new SinaOAuth object instance. different from the previous one, we need to pass in the obtained token data as a parameter object. Then, we should be able to get an access token. The obtained data should be an array, and this access token is the only data we need to save.

Create callback. php

<? Phpsession_start (); include_once ('config. php'); include_once ('weibooauth. php'); if (! Empty ($ _ GET ['oss _ verifier ']) &! Empty ($ _ SESSION ['keys'] ['auth _ token']) &! Empty ($ _ SESSION ['keys '] ['oss _ token']) {// SinaOAuth object instance. Pay attention to the newly added two parameters $ sinaOAuth = new WeiboOAuth (WB_AKEY, WB_SKEY, $ _ SESSION ['keys '] ['oss _ token'], $ _ SESSION ['keys'] ['oss _ token_secret ']); // get access token $ access_token = $ sinaOAuth-> getAccessToken ($ _ REQUEST ['oss _ verifier ']); // Save the obtained access token to the Session $ _ SESSION ['Access _ token'] = $ access_token; // obtain the user information $ user_info = $ sinaOAuth-> ge T ('account/verify_credentials '); // print the user information mysql_connect (DATABASE_HOST, DATABASE_USER, DATABASE_PSSWORD); mysql_select_db (DATABASE_DB_NAME); // replace it with your database connection in config. in 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 = 'sin A' 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 ['oss _ token']. "','". $ access_toke N ['auth _ 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 ['oss _ token']. "', oauth_secret = '". $ access_token ['auth _ token_secret ']. "'where oauth_provider = 'sina' D oauth_uid = ". $ user_info ['id']);} $ _ SESSION ['id'] = $ result ['id']; $ _ SESSION ['username'] = $ result ['username']; $ _ SESSION ['oss _ uid'] = $ result ['oss _ uid']; $ _ SESSION ['oss _ provider'] = $ result ['oss _ provider']; $ _ SESSION ['oss _ token'] = $ result ['oss _ token']; $ _ SESSION ['oss _ secret'] = $ result ['oss _ secret']; header ('location: update. php ') ;}} else {// The data is incomplete. Go to the header ('location: index. php ');} ?>

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

It should be noted that the parameter oauth_verifier passed back cannot be reused. If the above Code has correctly output user information, you can try to refresh the page again, the page will throw an error message because oauth_verifier has been used once. To use it again, you need to initiate a new authentication request on the index. php page.

User Registration

After obtaining the user information, we need to register the user information in our own database, provided that the user has not been registered in the local database.

The database link information in the code above should be changed to your own. If the user already exists in our database, We need to update the tokens field of the user, because it indicates that Twitter has generated a new tokens and the tokens in the database has 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:

Note that the SQL statements in the above Code have not been verified, and you may need to modify them in actual use. Before connecting to the database, we need to verify whether the user has logged on. With the username, We can display a personalized Welcome Message:

<? Phpinclude_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"> 

This is the main process of OAuth authentication and storage, and I hope to help you. Download Code: SinaOauth

The above is all the content described in this article. I hope you will like it.

Please take a moment to share your article with your friends or leave a comment. Thank you for your support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.