PHP搭建OAuth服務


自己寫OAuth后台太麻煩,直接拉取gitbub現成的。拉取活躍度比較高的bshaffer/oauth2-server-php

注:以下編碼是Oauth四種認證中的第四種:憑證式。想了解其他幾種方式,請移步阮一峰大大的博客http://www.ruanyifeng.com/blog/2019/04/oauth-grant-types.html?utm_source=tuicool&utm_medium=referral

1、首先拉取代碼 https://github.com/bshaffer/oauth2-server-php.git

2、在編碼之前先導入數據庫

CREATE TABLE `oauth_clients` (
  `client_id` varchar(80) NOT NULL,
  `client_secret` varchar(80) DEFAULT NULL,
  `redirect_uri` varchar(2000) DEFAULT NULL,
  `grant_types` varchar(80) DEFAULT NULL,
  `scope` varchar(4000) DEFAULT NULL,
  `user_id` varchar(80) DEFAULT NULL,
  PRIMARY KEY (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_jwt` (
  `client_id` varchar(80) NOT NULL,
  `subject` varchar(80) DEFAULT NULL,
  `public_key` varchar(2000) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_refresh_tokens` (
  `refresh_token` varchar(40) NOT NULL,
  `client_id` varchar(80) NOT NULL,
  `user_id` varchar(80) DEFAULT NULL,
  `expires` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `scope` varchar(4000) DEFAULT NULL,
  PRIMARY KEY (`refresh_token`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_scopes` (
  `scope` varchar(80) NOT NULL,
  `is_default` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`scope`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_users` (
  `username` varchar(80) DEFAULT NULL,
  `password` varchar(80) DEFAULT NULL,
  `first_name` varchar(80) DEFAULT NULL,
  `last_name` varchar(80) DEFAULT NULL,
  `email` varchar(80) DEFAULT NULL,
  `email_verified` tinyint(1) DEFAULT NULL,
  `scope` varchar(4000) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_access_tokens` (
  `access_token` varchar(40) NOT NULL,
  `client_id` varchar(80) NOT NULL,
  `user_id` varchar(80) DEFAULT NULL,
  `expires` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `scope` varchar(4000) DEFAULT NULL,
  PRIMARY KEY (`access_token`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

3、在站點創建oauthConf.php(創建和配置OAuth的實例)

$conf = [
    'dsn' => 'mysql:dbname=open;host=127.0.0.1:3808',
    'username' => 'root',
    'password' => 'root'
];

// Autoloading (composer is preferred, but for this example let's just do this)
require_once('oauth2-server/src/OAuth2/Autoloader.php');
OAuth2\Autoloader::register();

// $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
$storage = new OAuth2\Storage\Pdo($conf);

// Pass a storage object or array of storage objects to the OAuth2 server class
$server = new OAuth2\Server($storage);

// Add the "Client Credentials" grant type (it is the simplest of the grant types)
$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));

// Add the "Authorization Code" grant type (this is where the oauth magic happens)
$server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage));

4、獲取令牌前,先向數據庫插入一條測試數據

INSERT INTO oauth_clients (client_id, client_secret, redirect_uri) VALUES ("arthurtest", "arthurpass", "http://arthur/");

 

5、創建getToken.php(注:使用POST方法獲取accessToken)

<?php
// include our OAuth2 Server object
require_once __DIR__.'/server.php';

// Handle a request for an OAuth2.0 Access Token and send the response to the client
$server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();

6、執行getToken.php 獲得access_token(注:需傳入基本參數如下):

參數:

respose_type  authorization_code 標准的授權模式  password 基於用戶密碼的授權模式  client_credentials 基於密鑰的授權模式  refresh_token 刷新token
client_id 應用id
redirect_uri 回調地址

 

 

 

 

結果:

{
    "access_token": "20dc6de50b4136430a4b391e49cb7f7d94e2fdf6",
    "expires_in": 3600,
    "token_type": "Bearer",
    "scope": null
}

7、現在已經拿到了令牌,就可以調用接口了,我們可以使用以下代碼進行token合法驗證

<?php
// include our OAuth2 Server object
require_once __DIR__.'/server.php';

// Handle a request to a resource and authenticate the access token
if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
    $server->getResponse()->send();
echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM