天猫精灵开发OAuth2.0认证服务器搭建

1 环境说明

  1. 服务器:阿里云VPS
  2. 操作系统:CentOS7

2 安装httpd+mariadb+php,启动httpd

yum install httpd mariadb mariadb-server php php-mysql php-pdo -y
systemctl start httpd
天猫精灵开发OAuth2.0认证服务器搭建
天猫精灵开发OAuth2.0认证服务器搭建

3 部署OAuth2.0认证环境

3.1 下载OAuth2.0认证代码,将其拷贝到/var/www/html/

git clone https://github.com/bshaffer/oauth2-server-php.git -b master
cp -rf oauth2-server-php /var/www/html/

3.2 在mysql中创建数据库oauth2_db,并在数据库中创建如下表:

CREATE TABLE oauth_clients (
  client_id             VARCHAR(80)   NOT NULL,
  client_secret         VARCHAR(80),
  redirect_uri          VARCHAR(2000),
  grant_types           VARCHAR(80),
  scope                 VARCHAR(4000),
  user_id               VARCHAR(80),
  PRIMARY KEY (client_id)
);

CREATE TABLE oauth_access_tokens (
  access_token         VARCHAR(40)    NOT NULL,
  client_id            VARCHAR(80)    NOT NULL,
  user_id              VARCHAR(80),
  expires              TIMESTAMP      NOT NULL,
  scope                VARCHAR(4000),
  PRIMARY KEY (access_token)
);

CREATE TABLE oauth_authorization_codes (
  authorization_code  VARCHAR(40)     NOT NULL,
  client_id           VARCHAR(80)     NOT NULL,
  user_id             VARCHAR(80),
  redirect_uri        VARCHAR(2000),
  expires             TIMESTAMP       NOT NULL,
  scope               VARCHAR(4000),
  id_token            VARCHAR(1000),
  PRIMARY KEY (authorization_code)
);

CREATE TABLE oauth_refresh_tokens (
  refresh_token       VARCHAR(40)     NOT NULL,
  client_id           VARCHAR(80)     NOT NULL,
  user_id             VARCHAR(80),
  expires             TIMESTAMP       NOT NULL,
  scope               VARCHAR(4000),
  PRIMARY KEY (refresh_token)
);

CREATE TABLE oauth_users (
  username            VARCHAR(80),
  password            VARCHAR(80),
  first_name          VARCHAR(80),
  last_name           VARCHAR(80),
  email               VARCHAR(80),
  email_verified      BOOLEAN,
  scope               VARCHAR(4000),
  PRIMARY KEY (username)
);

CREATE TABLE oauth_scopes (
  scope               VARCHAR(80)     NOT NULL,
  is_default          BOOLEAN,
  PRIMARY KEY (scope)
);

CREATE TABLE oauth_jwt (
  client_id           VARCHAR(80)     NOT NULL,
  subject             VARCHAR(80),
  public_key          VARCHAR(2000)   NOT NULL
);
天猫精灵开发OAuth2.0认证服务器搭建
天猫精灵开发OAuth2.0认证服务器搭建

3.3 引导OAuth2.0服务器

  1. 创建/var/www/html/server.php,内容如下:
<?php
  /** 配置 */ 
$dsn= 'mysql:dbname=oauth2db;host=localhost';
$username = 'root';
$password = '123456';

// 错误报告(这毕竟是一个演示!)
ini_set('display_errors',1);error_reporting(E_ALL);

// 自动加载
require_once('oauth2-server-php/src/OAuth2/Autoloader.php');
OAuth2\Autoloader::register();
$storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));

// 通过存储对象或对象数组存储的oauth2服务器类
$server = new OAuth2\Server($storage);

// 授权码 有效期只有30秒
$server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage));

// 客户端证书
$server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));

// 用户凭据
$server->addGrantType(new OAuth2\GrantType\UserCredentials($storage));
// 刷新令牌  启用这个会报错,原因未知
// $server->addGrantType(new OAuth2\GrantType\RefreshToken($refreshStorage))
  1. 创建/var/www/html/token.php,内容如下:
<?php
 // include our OAuth2 Server object
require_once __DIR__.'/server.php';

$server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();
  1. 运行sql命令:

天猫精灵开发OAuth2.0认证服务器搭建

  1. 创建/var/www/html/resource.php,内容如下:
<?php

 //资源控制器的建立和测试
require_once __DIR__.'/server.php';

if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
        $server->getResponse()->send();
            die;
}
$token = $server->getAccessTokenData(OAuth2\Request::createFromGlobals());
echo "User ID associated with this token is {$token['user_id']}";

echo json_encode(array('success' => true, 'message' => '您访问了我的API!'));
  1. 创建/var/www/html/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();
  1. 获取Authorization Code(浏览器输入:http://localhost/authorize.php?response_type=code&client_id=testclient&state=xyz)

天猫精灵开发OAuth2.0认证服务器搭建

  1. 获取access_token(在3.6结束后的30s内完成此操作):

天猫精灵开发OAuth2.0认证服务器搭建