PHP搭建OAuth服務

本身寫OAuth後臺太麻煩,直接拉取gitbub現成的。拉取活躍度比較高的bshaffer/oauth2-server-phpphp

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

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

二、在編碼以前先導入數據庫git

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;

三、在站點建立oauthConf.php(建立和配置OAuth的實例)github

$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));

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

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

 

五、建立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();

六、執行getToken.php 得到access_token(注:需傳入基本參數以下):json

參數:app

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

 

 

 

 

結果:composer

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

七、如今已經拿到了令牌,就能夠調用接口了,咱們可使用如下代碼進行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!'));
相關文章
相關標籤/搜索