search
HomeBackend DevelopmentPHP TutorialOAuth2 builds a simple case based on TP

Reading instructions: Understanding OAuth2

OAuth is about authorization ( authorization) The open network standard is widely used around the world. The current version is version 2.0. Try to set up the environment today. This is only for learning records;

Reference source:

http://oauth.net/2/

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

Data table preparation:

--
-- 表的结构 `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`);

OAuth2 library address: https://github.com/bshaffer/oauth2-server-php

Here I put it in Vendor/OAuth2 ;

Authorization request class:

<?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->validateAuthorizeRequest($this->oauth_request, $this->oauth_response)) {
            $this->oauth_response->send();
            die;
        }


// print the authorization code if the user has authorized your client
        $this->oauth_server->handleAuthorizeRequest($this->oauth_request, $this->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->oauth_response->getHttpHeader('Location'), strpos($this->oauth_response->getHttpHeader('Location'), 'code=') + 5, 40);

        echo json_encode(['code' => $code]);

        //$this->oauth_response->send();
    }

    public function token()
    {
        $this->oauth_server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();
    }

}

OAuth2 library request encapsulation is placed in: Org/OAuth2;

<?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' => C('DSN'), 'username' => C('USERNAME'), 'password' => C('PASSWORD')));

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

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

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

        $this->oauth_request = \OAuth2\Request::createFromGlobals();
        $this->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->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {
            $this->oauth_server->getResponse()->send();
            die;
        }

        $this->tokenData = $this->oauth_server->getResourceController()->getToken();
    }

}

Test class:

<?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' => 'You accessed my APIs!'));
    }

    public function getToken()
    {
        echo json_encode(['token' => $this->tokenData]);
    }

}

Configuration file:

require_once(VENDOR_PATH . '/OAuth2/Autoloader.php');
OAuth2\Autoloader::register();
return array(
    //'配置项'=>'配置值'
    'AUTOLOAD_NAMESPACE' => array('OAuth2' => VENDOR_PATH . 'OAuth2/'), //扩展模块列表
    'DSN' => 'mysql:host=localhost;dbname=oauth2',
    'USERNAME' => 'root',
    'PASSWORD' => '',
);

The above introduces a simple case of building OAuth2 based on TP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP开发:使用 Laravel Passport 实现 OAuth2 服务提供者PHP开发:使用 Laravel Passport 实现 OAuth2 服务提供者Jun 15, 2023 pm 04:32 PM

随着移动互联网的普及,越来越多的应用程序都需要用户进行身份验证和授权。OAuth2是一种流行的认证和授权框架,它为应用程序提供了一种标准化的机制来实现这些功能。LaravelPassport是一个易于使用,安全且开箱即用的OAuth2服务器实现,它为PHP开发人员提供了构建OAuth2身份验证和授权的强大工具。本文将介绍LaravelPassport的使

PHP和OAuth:实现微软登录集成PHP和OAuth:实现微软登录集成Jul 28, 2023 pm 05:15 PM

PHP和OAuth:实现微软登录集成随着互联网的发展,越来越多的网站和应用程序需要支持用户使用第三方账号登录,以提供方便的注册和登录体验。微软账号是全球范围内广泛使用的账号之一,许多用户希望使用微软账号登录网站和应用程序。为了实现微软登录集成,我们可以使用OAuth(开放授权)协议来实现。OAuth是一种开放标准的授权协议,允许用户授权第三方应用程序代表自己

PHP中的OAuth:创建一个JWT授权服务器PHP中的OAuth:创建一个JWT授权服务器Jul 28, 2023 pm 05:27 PM

PHP中的OAuth:创建一个JWT授权服务器随着移动应用和前后端分离的趋势的兴起,OAuth成为了现代Web应用中不可或缺的一部分。OAuth是一种授权协议,通过提供标准化的流程和机制,用于保护用户的资源免受未经授权的访问。在本文中,我们将学习如何使用PHP创建一个基于JWT(JSONWebTokens)的OAuth授权服务器。JWT是一种用于在网络中

Laravel开发:如何使用Laravel Passport实现API OAuth2身份验证?Laravel开发:如何使用Laravel Passport实现API OAuth2身份验证?Jun 13, 2023 pm 11:13 PM

随着API的使用逐渐普及,保护API的安全性和可扩展性变得越来越关键。而OAuth2已经成为了一种广泛采用的API安全协议,它允许应用程序通过授权来访问受保护的资源。为了实现OAuth2身份验证,LaravelPassport提供了一种简单、灵活的方式。在本篇文章中,我们将学习如何使用LaravelPassport实现APIOAuth2身份验证。Lar

利用PHP实现OAuth2.0的最佳方式利用PHP实现OAuth2.0的最佳方式Jun 08, 2023 am 09:09 AM

OAuth2.0是一种用来授权第三方应用程序访问用户资源的协议,现已被广泛应用于互联网领域。随着互联网业务的发展,越来越多的应用程序需要支持OAuth2.0协议。本文将介绍利用PHP实现OAuth2.0协议的最佳方式。一、OAuth2.0基础知识在介绍OAuth2.0的实现方式之前,我们需要先了解一些OAuth2.0的基础知识。授权类型OAuth2.0协议定

Java API 开发中使用 Spring Security OAuth2 进行鉴权Java API 开发中使用 Spring Security OAuth2 进行鉴权Jun 18, 2023 pm 11:03 PM

随着互联网的不断发展,越来越多的应用程序都采用了分布式的架构方式进行开发。而在分布式架构中,鉴权是最为关键的安全问题之一。为了解决这个问题,开发人员通常采用的方式是实现OAuth2鉴权。SpringSecurityOAuth2是一个常用的用于OAuth2鉴权的安全框架,非常适合于JavaAPI开发。本文将介绍如何在JavaAPI开发

php如何使用OAuth2?php如何使用OAuth2?Jun 01, 2023 am 08:31 AM

OAuth2是一个广泛使用的开放标准协议,用于在不将用户名和密码直接传输到第三方应用程序的情况下授权访问他们的用户资源,例如Google,Facebook和Twitter等社交网络。在PHP中,您可以使用现成的OAuth2库来轻松地实现OAuth2流程,或者您可以构建自己的库来实现它。在本文中,我们将重点关注使用现成的OAuth2库,如何通过它来使用OAut

PHP中如何使用GuzzleHttp进行OAuth2认证PHP中如何使用GuzzleHttp进行OAuth2认证Jun 27, 2023 pm 02:48 PM

随着互联网技术的不断发展,越来越多的应用需要进行OAuth2认证,其中PHP中的GuzzleHttp是一种常用的HTTP请求库,如何使用GuzzleHttp进行OAuth2认证呢?本文将详细介绍GuzzleHttp的OAuth2认证相关使用方法。1.安装GuzzleHttp使用Composer安装GuzzleHttp:composerrequireguz

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)