How use oauth 2.0 for rest api calls in php?

REST APIs are a big part of today’s Internet. Some of the everyday use cases of REST APIs are:

  • driving the backend of single-page Web applications/mobile applications
  • integrating different applications to exchange data and automate workflows
  • providing the communication channel for the different parts of a complex service-oriented architecture
  • connecting IoT devices.

REST API security is essential because an API can expose powerful, mission-critical, and outright dangerous functionality over the Internet. For example, a fintech SaaS application might offer an API that allows you to manipulate your bank accounts, make payments, transfer funds abroad, or download sensitive information like your bank statements, personal address/name/SSN.

Most Web application frameworks provide tools to build secure REST APIs quickly using industry-standard solutions like JSON Web Tokens [JWT] and OAuth 2.0. However, it pays to understand what goes under the hood and how to authenticate and authorize your API users securely. In this tutorial, I’ll walk you through building a simple API in PHP from scratch and integrating it with Okta to provide user authentication. Okta is an API service that allows you to create, edit, and securely store user accounts and user account data, and connect them with one or more applications.

The tutorial will not rely on any external libraries to implement the Okta integration or to work with the JWT access tokens. The only prerequisites are PHP, Composer, and a free Okta developer account.

Create the REST API Skeleton

Start by creating a blank project with a /src directory and a composer.json file on the top level:

In the composer.json file, define one dependency [the DotEnv library so you can keep the Okta authentication details in a .env file that’s ignored by Git]. In addition to the dependency, define a PSR-4 autoloader to automatically look for PHP classes in the /src directory of the project:

composer.json

{
    "require": {
        "vlucas/phpdotenv": "^2.4"
    },
    "autoload": {
        "psr-4": {
            "Src\\": "src/"
        }
    }
}

Install the dependencies:

This will create a /vendor directory and install DotEnv inside it.

Create a .gitignore file on the top level so the /vendor directory and the local .env file will be ignored:

.gitgignore

Create a .env.example file for the Okta authentication variables:

OKTA_CLIENT_ID=
OKTA_CLIENT_SECRET=
OKTA_AUDIENCE=api://default
OKTA_ISSUER=
OKTA_SCOPE=
OKTA_SERVICE_APP_ID=
OKTA_SERVICE_APP_SECRET=

There are two sets of credentials - one for the Service application [the REST API], and one for the Client application which will make use of the API. Some of the variables will be shared between the two applications [the Issuer, Scope, and Audience].

Create a bootstrap.php file which loads the environment variables [later it will also do some additional bootstrapping for our project]:

Chủ Đề