1. 程式人生 > >php建立oauth2 server

php建立oauth2 server

Step-By-Step Walkthrough

The following instructions provide a detailed walkthrough to help you get an OAuth2 server up and running. To see the codebase of an existing OAuth2 server implementing this library, check out the OAuth2 Demo.

Initialize your Project

Create a directory for your project and pull in this library

text
mkdir my-oauth2-walkthrough
cd my-oauth2-walkthrough
git clone https://github.com/bshaffer/oauth2-server-php.git -b master

Define your Schema

Now use the following schema to create the default database:

MySQL / SQLite / PostgreSQL / MS SQL Server

sql
CREATE TABLE oauth_clients (client_id VARCHAR
(80) NOT NULL, client_secret VARCHAR(80), redirect_uri VARCHAR(2000) NOT NULL, grant_types VARCHAR(80), scope VARCHAR(100), user_id VARCHAR(80), CONSTRAINT clients_client_id_pk PRIMARY KEY (client_id)); CREATE TABLE oauth_access_tokens (access_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR
(255), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT access_token_pk PRIMARY KEY (access_token)); CREATE TABLE oauth_authorization_codes (authorization_code VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), redirect_uri VARCHAR(2000), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT auth_code_pk PRIMARY KEY (authorization_code)); CREATE TABLE oauth_refresh_tokens (refresh_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT refresh_token_pk PRIMARY KEY (refresh_token)); CREATE TABLE oauth_users (username VARCHAR(255) NOT NULL, password VARCHAR(2000), first_name VARCHAR(255), last_name VARCHAR(255), CONSTRAINT username_pk PRIMARY KEY (username)); CREATE TABLE oauth_scopes (scope TEXT, is_default BOOLEAN); CREATE TABLE oauth_jwt (client_id VARCHAR(80) NOT NULL, subject VARCHAR(80), public_key VARCHAR(2000), CONSTRAINT jwt_client_id_pk PRIMARY KEY (client_id));

Bootstrap your OAuth2 Server

We need to create and configure our OAuth2 Server object. This will be used by all the endpoints in our application. Name this file server.php:

php
$dsn      = 'mysql:dbname=my_oauth2_db;host=localhost';
$username = 'root';
$password = '';

// error reporting (this is a demo, after all!)
ini_set('display_errors',1);error_reporting(E_ALL);

// Autoloading (composer is preferred, but for this example let's just do this)
require_once('oauth2-server-php/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(array('dsn' => $dsn, 'username' => $username, 'password' => $password));

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

Note: Be sure to define the $dsn$username, and $password variables to be the appropriate values for your database.

Create a Token Controller

Next, we will create the Token Controller. This is the URI which returns an OAuth2.0 Token to the client. Here is an example of a token controller in the file token.php:

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

Congratulatons! You have created a Token Controller! Do you want to see it in action? Run the following SQL to create an OAuth Client:

sql
INSERT INTO oauth_clients (client_id, client_secret, redirect_uri) VALUES ("testclient", "testpass", "http://fake/");

Now run the following from the command line:

text
curl -u testclient:testpass http://localhost/token.php -d 'grant_type=client_credentials'

Note: http://localhost/token.php assumes you have the file token.php on your local machine, and you have set up the “localhost” webhost to point to it. This may vary for your application.

If everything works, you should receive a response like this:

json
{"access_token":"03807cb390319329bdf6c777d4dfae9c0d3b3c35","expires_in":3600,"token_type":"bearer","scope":null}

Create a Resource Controller

Now that you are creating tokens, you’ll want to validate them in your APIs. Here is an example of a resource controller in the file resource.php:

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();
    die;
}
echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));

Now run the following from the command line:

text
curl http://localhost/resource.php -d 'access_token=YOUR_TOKEN'

Note: Use the value returned in “access_token” from the previous step in place of YOUR_TOKEN

If all goes well, you should receive a response like this:

json
{"success":true,"message":"You accessed my APIs!"}

Authorize Controllers are the “killer feature” of OAuth2, and allow for your users to authorize third party applications. Instead of issuing an Access Token straightaway as happened in the first token controller example, in this example an authorize controller is used to only issue a token once the user has authorized the request. Create authorize.php:

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

$request = OAuth2\Request::createFromGlobals();
$response = new OAuth2\Response();

// validate the authorize request
if (!$server->validateAuthorizeRequest($request, $response)) {
    $response->send();
    die;
}
// display an authorization form
if (empty($_POST)) {
  exit('
<form method="post">
  <label>Do You Authorize TestClient?</label><br />
  <input type="submit" name="authorized" value="yes">
  <input type="submit" name="authorized" value="no">
</form>');
}

// print the authorization code if the user has authorized your client
$is_authorized = ($_POST['authorized'] === 'yes');
$server->handleAuthorizeRequest($request, $response, $is_authorized);
if ($is_authorized) {
  // 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($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
  exit("SUCCESS! Authorization Code: $code");
}
$response->send();

Now paste the following URL in your browser

text
http://localhost/authorize.php?response_type=code&client_id=testclient&state=xyz

You will be prompted with an authorization form, and receive an authorization code upon clicking “yes”

The Authorization Code can now be used to receive an access token from your previously created token.phpendpoint. Just call this endpoint using the returned authorization code:

text
curl -u testclient:testpass http://localhost/token.php -d 'grant_type=authorization_code&code=YOUR_CODE'

And just as before, you will receive an access token:

json
{"access_token":"6f05ad622a3d32a5a81aee5d73a5826adb8cbf63","expires_in":3600,"token_type":"bearer","scope":null}

Note: Be sure to do this quickly, because Authorization Codes expire in 30 seconds!

Associating local users with access tokens

Once you’ve authenticated a user and issued an access token (such as with the above Authorize Controller example), you’ll probably want to know which user an access token applies to when it is used. Have a look at theUser ID documentation for information on how to do this.

If you want to test the authorize controller using a “real” client, check out the Google OAuth2 Playground example


相關推薦

php建立oauth2 server

Step-By-Step Walkthrough The following instructions provide a detailed walkthrough to help you get an OAuth2 server up and running.

使用 OAuth2-Server-php 搭建 OAuth2 Server

clas 特點 a10 直線 編碼 信任關系 nbsp 身份驗證 引導 Yii 有很多 extension 可以使用,在查看了 Yii 官網上提供的與 OAuth 相關的擴展後,發現了幾個 OAuth2 的客戶端擴展,但是並沒有找到可以作為 OAuth2 Serve

oauth2-server-php-docs 授權控制器

hub php 對象 cer 應用 eth 重定向 受保護 配置 授權控制器 概觀 對於授權端點,要求用戶使用authorization code(授權碼授權類型)或access token(隱式授權類型)對客戶端進行認證和重定向。 方法 handleAuthori

oauth2-server-php-docs 授權類型

rst 憑證 希望 第三方 define foo pan 進行 4.2 授權碼 概觀 在Authorization Code交付式時使用的客戶端想要請求訪問受保護資源代表其他用戶(即第三方)。這是最常與OAuth關聯的授予類型。 詳細了解授權碼 用例 代表第三

oauth2-server-php-docs 存儲

列表 ons () driver postgresq 控制器 ati ntc mod PDO 概觀 PDO存儲類使用 PHP 的PDO擴展。這允許連接到MySQL,SQLite,PostgreSQL 等等。 安裝 PDO是默認安裝的php 5.1+,這個庫已經是必需

Oauth2.0 oauth2-server-php的使用Demo,怎麼連線redis/可實現thinkphp5/yii/Laravel中使用

單點登入SSO 本片教程沒有華麗的說辭,只有實實在在的程式碼: https://github.com/liaoshengping/oauth2-php 如果你沒有接觸oauth2.0,先無腦用原生php的跑一邊,方便理解 Oauth2.0 開發準備: 下載之後先執行:co

使用OAuth Server PHP實現OAuth2服務

在現在的網路服務中,OAuth2.0服務已經很普遍了,無論是facebook或者微博的第三方登入,還是手機APP登入,都有很廣泛的應用。 它主要的目的如下: 如果使用者的照片在A網站,他想要在B網站使用A網站的頭像,並不需要向B網站提供自己在A網站的使用者名稱和密

Oauth2.0 oauth2-server-php的使用Demo,怎麼連線redis/可實現thinkphp5/yii/Laravel中使用

單點登入SSO 開發準備: 下載之後先執行:composer update 1.資料庫匯入 2.在service.php 設定資料庫資訊 3.notice:在host 設定 oauth2.com 指向本地 post引數: client_id:testcl

使用 OAuth2-Server-php 在 Yii 框架上搭建 OAuth2 Server

http://www.cnblogs.com/rereadyou/p/3448381.html Yii 有很多 extension 可以使用,在查看了 Yii 官網上提供的與 OAuth 相關的擴充套件後,發現了幾個 OAuth2 的客戶端擴充套件,但

centos7上建立vnc server

名稱 splay systemctl pla /dev/ 開啟 service pan bsp centos7跟6比設置方法不一樣 yum groupinstall "X Window System" -yyum grouplistyum groupinstall "GNO

使用Identity Server 4建立Authorization Server (2)

可能 參數 ecif fig register startup 類型 cal mat 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第一部分主要是建立了一個簡單的Identity Server. 接下來繼續: 建立Web

使用Identity Server 4建立Authorization Server (5)

連接字符串 mapr path 框架 ise network edit setting pin 預備知識: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780

使用Identity Server 4建立Authorization Server (6) - js(angular5) 客戶端

include 節點 ogr 包含 發的 for icon ets list 預備知識: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html

think PHP建立資料庫表,資料庫表更名

引用 use think\Db; 建立表方法 public function createTable($tableName) { $sql = "CREATE TABLE IF NOT EXISTS `$tableName` ( `id` in

PHP建立圖片驗證碼

程式碼如下: <?php header("Content-type: text/html; charset=utf8"); /*  * 函式名:createImage  * 描述:獲取驗證圖片驗證碼  * @param $width 畫布的寬 &nbs

3行程式碼快速實現Spring Boot Oauth2 Server服務

這裡的3行程式碼並不是指真的只需要寫3行程式碼,而是基於我已經寫好的一個Spring Boot Oauth2服務。僅僅需要修改3行資料庫配置資訊,即可得到一個Spring Boot Oauth2服務。 專案地址https://github.com/jeesun/oauthserver

初試PHP連線sql server

最開始想使用 pdo_sqlsrv 拓展,但是一直沒成功,本文采用的是 pdo_dblib + freetds。 環境:CentOS 6.8、PHP 5.6.20   freetds 1 wget ftp://ftp.freetds.org/pub/freetds/

php建立XML

php建立XML a.xml: <?xml version="1.0" encoding="utf-8"?> <root> <title attr="good"> <a>我是a</a> <b><![C

通過 Ansible 建立 Jenkins Server

Ansible roles(角色) Ansible 中除了 playbook,還有更高層級的抽象,稱為 role(角色)。所謂的 role 其實就是把一些 playbook 組織成為一個更簡潔、清晰的可重用物件。比如把安裝 Jenkins Server 的 playbook 組織成為一個 role。感謝開源

php 建立多級目錄

/** * 建立多級目錄 * @param $path string 要建立的目錄 * @param $mode int 建立目錄的模式,在windows下可忽略 */ function create_dir($path,$mode = 0777) { if (is_dir($path)