Home >Backend Development >PHP Tutorial >Detailed explanation of the main processes of Sina Weibo OAuth authentication and storage_PHP tutorial

Detailed explanation of the main processes of Sina Weibo OAuth authentication and storage_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:59:501019browse

Detailed explanation of the main process of Sina Weibo OAuth authentication and storage

This article introduces to you a detailed explanation of the main process of Sina Weibo OAuth authentication and storage implemented with reference to Twitter's authentication process.

There are many articles about OAuth on the Internet, but none including sina itself has a detailed introduction, including the verification process and the 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:

?

1

2

3

4

5

6

7

8

9

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;

1 2

3

4

5

6

7

8

9

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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;

?>

Use Oauth to login

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 ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <🎜>session_start();<🎜> <🎜>//if( isset($_SESSION['last_key']) )<🎜> <🎜>header("Location: weibolist.php");<🎜> <🎜>include_once( 'config.php' );<🎜> <🎜>include_once( 'weibooauth.php' );<🎜> <🎜>//Create 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['oauth_token'] ,false , 'http://t.yourtion.com/sina/callback.php'); //Save to session $_SESSION['keys'] = $keys; ?> Use Oauth to login

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

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 object instance, note the two newly added parameters

$sinaOAuth = new WeiboOAuth(WB_AKEY, WB_SKEY, $_SESSION['keys']['oauth_token'],

$_SESSION['keys']['oauth_token_secret']);

//Get access token

$access_token = $sinaOAuth->getAccessToken($_REQUEST['oauth_verifier']);

// Save the obtained access token into Session

$_SESSION['access_token'] = $access_token;

// Get user information

$user_info = $sinaOAuth->get('account/verify_credentials');

//Print user information

mysql_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PSSWORD);

mysql_select_db(DATABASE_DB_NAME);

//Replace with your database connection in 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

{

//The data is incomplete, go to the previous step

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 may need to be modified 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:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

include_once ('config.php');

include_once ('weibooauth.php');

session_start();

if(!empty($_SESSION['username'])){

// User is logged in, redirect

header('index.php');

}

?>

通过 OAuth 进行身份验证--Yourtion

Hello

1 2

3

4

5 6

78 9 10 11 12 13
14
15
16 17 18
<🎜>include_once ('config.php');<🎜> <🎜>include_once ('weibooauth.php');<🎜> <🎜>session_start();<🎜> <🎜>if(!empty($_SESSION['username'])){<🎜> <🎜>// User is logged in, redirect<🎜> <🎜>header('index.php');<🎜> <🎜>}<🎜> <🎜>?> Authenticate via OAuth--Yourtion

Hello

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. http://www.bkjia.com/PHPjc/975131.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/975131.htmlTechArticleDetailed explanation of the main process of Sina Weibo OAuth authentication and storage. This article introduces to you the implementation of the authentication process with reference to Twitter The main processes of Sina Weibo OAuth authentication and storage are explained in detail online...
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