Rumah pembangunan bahagian belakang tutorial php OAuth2 基于TP 搭建简单案例

OAuth2 基于TP 搭建简单案例

Jul 29, 2016 am 08:56 AM
default gt oauth server this

阅读须知:理解OAuth2

OAuth是一个关于授权(authorization)的开放网络标准,在全世界得到广泛应用,目前的版本是2.0版。今天就试着把环境搭建一下在此仅作为学习记录;

参考资料来源:

http://oauth.net/2/

http://bshaffer.github.io/oauth2-server-php-docs/cookbook/

数据表准备:

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

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

--

-- 表的结构 `oauth_access_tokens`

--

 

CREATE TABLE IF NOT EXISTS `oauth_access_tokens` (

  `access_token` text,

  `client_id` text,

  `user_id` text,

  `expires` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

  `scope` text

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

-- --------------------------------------------------------

 

--

-- 表的结构 `oauth_authorization_codes`

--

 

CREATE TABLE IF NOT EXISTS `oauth_authorization_codes` (

  `authorization_code` text,

  `client_id` text,

  `user_id` text,

  `redirect_uri` text,

  `expires` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

  `scope` text,

  `id_token` text

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

-- --------------------------------------------------------

 

--

-- 表的结构 `oauth_clients`

--

 

CREATE TABLE IF NOT EXISTS `oauth_clients` (

  `client_id` text,

  `client_secret` text,

  `redirect_uri` text

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

--

-- 转存表中的数据 `oauth_clients`

--

 

INSERT INTO `oauth_clients` (`client_id`, `client_secret`, `redirect_uri`) VALUES

('demoapp', 'demopass', 'http://127.0.0.1/tp/index.php');

 

-- --------------------------------------------------------

 

--

-- 表的结构 `oauth_public_keys`

--

 

CREATE TABLE IF NOT EXISTS `oauth_public_keys` (

  `client_id` varchar(80) DEFAULT NULL,

  `public_key` varchar(8000) DEFAULT NULL,

  `private_key` varchar(8000) DEFAULT NULL,

  `encryption_algorithm` varchar(80) DEFAULT 'RS256'

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

-- --------------------------------------------------------

 

--

-- 表的结构 `oauth_refresh_tokens`

--

 

CREATE TABLE IF NOT EXISTS `oauth_refresh_tokens` (

  `refresh_token` text,

  `client_id` text,

  `user_id` text,

  `expires` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

  `scope` text

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

-- --------------------------------------------------------

 

--

-- 表的结构 `oauth_scopes`

--

 

CREATE TABLE IF NOT EXISTS `oauth_scopes` (

  `scope` text,

  `is_default` tinyint(1) DEFAULT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

-- --------------------------------------------------------

 

--

-- 表的结构 `oauth_users`

--

 

CREATE TABLE IF NOT EXISTS `oauth_users` (

  `username` varchar(255) NOT NULL,

  `password` varchar(2000) DEFAULT NULL,

  `first_name` varchar(255) DEFAULT NULL,

  `last_name` varchar(255) DEFAULT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

--

-- Indexes for table `oauth_users`

--

ALTER TABLE `oauth_users`

  ADD PRIMARY KEY (`username`);

Salin selepas log masuk

OAuth2 库地址:https://github.com/bshaffer/oauth2-server-php

这里我把它放在Vendor/OAuth2里;

授权请求类:

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

<?php namespace Api\Controller;

 

class OAuth2Controller extends \Org\OAuth2\Controller

{

 

    public function __construct()

    {

        parent::__construct();

    }

 

    public function authorize()

    {

 

// validate the authorize request

        if (!$this->oauth_server-&gt;validateAuthorizeRequest($this-&gt;oauth_request, $this-&gt;oauth_response)) {

            $this-&gt;oauth_response-&gt;send();

            die;

        }

 

 

// print the authorization code if the user has authorized your client

        $this-&gt;oauth_server-&gt;handleAuthorizeRequest($this-&gt;oauth_request, $this-&gt;oauth_response, true);

 

        // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client

        $code = substr($this-&gt;oauth_response-&gt;getHttpHeader('Location'), strpos($this-&gt;oauth_response-&gt;getHttpHeader('Location'), 'code=') + 5, 40);

 

        echo json_encode(['code' =&gt; $code]);

 

        //$this-&gt;oauth_response-&gt;send();

    }

 

    public function token()

    {

        $this-&gt;oauth_server-&gt;handleTokenRequest(\OAuth2\Request::createFromGlobals())-&gt;send();

    }

 

}

Salin selepas log masuk

OAuth2 库的请求封装放在:Org/OAuth2里;

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

<?php namespace Org\OAuth2;

 

class Controller

{

 

    protected $oauth_server;

    protected $oauth_storage;

    protected $oauth_request;

    protected $oauth_response;

 

    public function __construct()

    {

        // Autoloading (composer is preferred, but for this example let's just do this)

//        require_once(VENDOR_PATH . '/OAuth2/Autoloader.php');

//        \OAuth2\Autoloader::register();

        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"

        $this->oauth_storage = new \OAuth2\Storage\Pdo(array('dsn' =&gt; C('DSN'), 'username' =&gt; C('USERNAME'), 'password' =&gt; C('PASSWORD')));

 

        // Pass a storage object or array of storage objects to the OAuth2 server class

        $this-&gt;oauth_server = new \OAuth2\Server($this-&gt;oauth_storage);

 

        // Add the "Client Credentials" grant type (it is the simplest of the grant types)

        $this-&gt;oauth_server-&gt;addGrantType(new \OAuth2\GrantType\ClientCredentials($this-&gt;oauth_storage));

 

        // Add the "Authorization Code" grant type (this is where the oauth magic happens)

        $this-&gt;oauth_server-&gt;addGrantType(new \OAuth2\GrantType\AuthorizationCode($this-&gt;oauth_storage));

 

        $this-&gt;oauth_request = \OAuth2\Request::createFromGlobals();

        $this-&gt;oauth_response = new \OAuth2\Response();

    }

 

}

 

 

<?php namespace Org\OAuth2;

 

class Resource extends Controller

{

 

    protected $tokenData;

 

    public function __construct()

    {

        parent::__construct();

 

        // Handle a request to a resource and authenticate the access token

        if (!$this->oauth_server-&gt;verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {

            $this-&gt;oauth_server-&gt;getResponse()-&gt;send();

            die;

        }

 

        $this-&gt;tokenData = $this-&gt;oauth_server-&gt;getResourceController()-&gt;getToken();

    }

 

}

Salin selepas log masuk

测试类:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?php namespace Api\Controller;

 

class TestController extends \Org\OAuth2\Resource

{

 

    public function __construct()

    {

        parent::__construct();

    }

 

    public function test()

    {

        echo json_encode(array('success' => true, 'message' =&gt; 'You accessed my APIs!'));

    }

 

    public function getToken()

    {

        echo json_encode(['token' =&gt; $this-&gt;tokenData]);

    }

 

}

Salin selepas log masuk

配置文件:

1

2

3

4

5

6

7

8

9

require_once(VENDOR_PATH . '/OAuth2/Autoloader.php');

OAuth2\Autoloader::register();

return array(

    //'配置项'=&gt;'配置值'

    'AUTOLOAD_NAMESPACE' =&gt; array('OAuth2' =&gt; VENDOR_PATH . 'OAuth2/'), //扩展模块列表

    'DSN' =&gt; 'mysql:host=localhost;dbname=oauth2',

    'USERNAME' =&gt; 'root',

    'PASSWORD' =&gt; '',

);

Salin selepas log masuk

以上就介绍了OAuth2 基于TP 搭建简单案例,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn

Tag artikel panas

Notepad++7.3.1

Notepad++7.3.1

Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina

SublimeText3 versi Cina

Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1

Hantar Studio 13.0.1

Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6

Dreamweaver CS6

Alat pembangunan web visual

SublimeText3 versi Mac

SublimeText3 versi Mac

Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Apakah perbezaan antara Huawei GT3 Pro dan GT4? Apakah perbezaan antara Huawei GT3 Pro dan GT4? Dec 29, 2023 pm 02:27 PM

Apakah perbezaan antara Huawei GT3 Pro dan GT4?

Betulkan: Alat snipping tidak berfungsi dalam Windows 11 Betulkan: Alat snipping tidak berfungsi dalam Windows 11 Aug 24, 2023 am 09:48 AM

Betulkan: Alat snipping tidak berfungsi dalam Windows 11

Cara memasang, menyahpasang dan menetapkan semula sandaran pelayan Windows Cara memasang, menyahpasang dan menetapkan semula sandaran pelayan Windows Mar 06, 2024 am 10:37 AM

Cara memasang, menyahpasang dan menetapkan semula sandaran pelayan Windows

OAuth dalam PHP: Mencipta Pelayan Kebenaran JWT OAuth dalam PHP: Mencipta Pelayan Kebenaran JWT Jul 28, 2023 pm 05:27 PM

OAuth dalam PHP: Mencipta Pelayan Kebenaran JWT

PHP dan OAuth: Melaksanakan Integrasi Log Masuk Microsoft PHP dan OAuth: Melaksanakan Integrasi Log Masuk Microsoft Jul 28, 2023 pm 05:15 PM

PHP dan OAuth: Melaksanakan Integrasi Log Masuk Microsoft

Cara melakukan penyepaduan Google Drive menggunakan PHP dan OAuth Cara melakukan penyepaduan Google Drive menggunakan PHP dan OAuth Jul 31, 2023 pm 04:41 PM

Cara melakukan penyepaduan Google Drive menggunakan PHP dan OAuth

Cara Membetulkan Ralat Tidak Dapat Menyambung ke App Store pada iPhone Cara Membetulkan Ralat Tidak Dapat Menyambung ke App Store pada iPhone Jul 29, 2023 am 08:22 AM

Cara Membetulkan Ralat Tidak Dapat Menyambung ke App Store pada iPhone

Versi pratonton Windows Server 2025 mengalu-alukan kemas kini, Microsoft menambah baik pengalaman ujian Insiders Versi pratonton Windows Server 2025 mengalu-alukan kemas kini, Microsoft menambah baik pengalaman ujian Insiders Feb 19, 2024 pm 02:36 PM

Versi pratonton Windows Server 2025 mengalu-alukan kemas kini, Microsoft menambah baik pengalaman ujian Insiders

See all articles