Home >Backend Development >PHP Tutorial >How to integrate OAuth 2.0 in PHP to secure API

How to integrate OAuth 2.0 in PHP to secure API

WBOY
WBOYOriginal
2023-06-17 10:49:281433browse

In current mobile and web applications, APIs are an essential part. They provide interactive interfaces for users and applications. However, these APIs also pose risks to malicious users and hackers, and can lead to the leakage of sensitive data. Therefore, APIs must be secured to prevent unauthorized access. OAuth 2.0 is a proven way to allow you to access an API through a token while ensuring that you are authorized to do so.

In this article, we will explore how to integrate OAuth 2.0 in PHP to secure APIs.

What is OAuth 2.0?

OAuth 2.0 is an open standard that allows users to authorize third parties to access their resources (e.g., photos, documents, contacts, etc.). More specifically, OAuth 2.0 uses authorization tokens to access their resources on behalf of users. An access token is a credential issued by an authorization server and provided to the caller when accessing a resource. Callers can use this token with each request to indicate that they are authorized to access the resource.

Integrating OAuth 2.0 in PHP

In PHP, there are many OAuth 2.0 libraries to choose from. In this article, we will introduce the process of implementing OAuth 2.0 using thephpleague/oauth2-client package.

Step 1: Install thephpleague/oauth2-client package

We first need to install thephpleague/oauth2-client package. It can be installed using the Composer package manager. Navigate to your project directory in a terminal or command line interface and run the following command there:

composer require league/oauth2-client

Step 2: Set up provider client

Now, we need to define the provider client end. Here we use the GitHub OAuth provider as an example. First, change the values ​​of the CLIENT_ID and CLIENT_SECRET constants with your actual application credentials.

<?php

require 'vendor/autoload.php';

use LeagueOAuth2ClientProviderGithub;

const CLIENT_ID = 'your_client_id';
const CLIENT_SECRET = 'your_client_secret';
const REDIRECT_URI = 'http://localhost/oauth2/callback.php';

$provider = new Github([
    'clientId'        => CLIENT_ID,
    'clientSecret'    => CLIENT_SECRET,
    'redirectUri'     => REDIRECT_URI,
]);

Step 3: Obtain the authorization code

Next, we need to obtain the authorization code. The authorization code is a temporary token used to verify identity when further obtaining an access token.

<?php

$authorizationUrl = $provider->getAuthorizationUrl([
    'scope' => ['user', 'repo', 'notifications']
]);

$_SESSION['oauth2state'] = $provider->getState();

header('Location: ' . $authorizationUrl);

In the code above, the getAuthorizationUrl() method returns an authorization URL, and jumping to this URL will direct the user to GitHub, asking them to provide an access token. When GitHub authorizes, it will reroute the user to a redirect URI that contains the authorization code.

Step 4: Obtain Access Token

Now, we need to obtain the access token using the authorization code we obtained in the previous step.

<?php

if (isset($_GET['code']) && isset($_GET['state']) && isset($_SESSION['oauth2state'])) {
    if ($_GET['state'] === $_SESSION['oauth2state']) {

        try {
            $token = $provider->getAccessToken('authorization_code', [
                'code' => $_GET['code']
            ]);

            $accessToken = $token->getToken();
            $refreshToken = $token->getRefreshToken();
            $expires = $token->getExpires();
        } catch (Exception $e) {
            exit('Failed to get access token: ' . $e->getMessage());
        }

        // Get the user object.
        try {
            $user = $provider->getResourceOwner($token);
            $name = $user->getName();
            $email = $user->getEmail();
            $imageUrl = $user->getAvatarUrl();
            $profileUrl = $user->getHtmlUrl();
        } catch (Exception $e) {
            exit('Failed to get user: ' . $e->getMessage());
        }

        // Store the access token and user data somewhere
        // for use in your application.
        $_SESSION['github_access_token'] = $accessToken;
        $_SESSION['github_refresh_token'] = $refreshToken;
        $_SESSION['github_expires'] = $expires;
        $_SESSION['github_user_name'] = $name;
        $_SESSION['github_user_email'] = $email;
        $_SESSION['github_user_image'] = $imageUrl;
        $_SESSION['github_user_profile_url'] = $profileUrl;

        // Redirect the user to the original page
        // or some other authorized page in your application.
        header('Location: /');
        exit();
    } else {
        exit('Invalid state');
    }
}

In the above code, we first use the getAccessToken() method to obtain the access token. Then, we use the getResourceOwner() method to get the user object. Finally, we store the user data and access token in the session.

Step 5: Call the API using the access token

Finally, we can call the protected API using the access token. In this example, we will use the GitHub API, which requires us to authenticate using an access token.

<?php

$client = new GuzzleHttpClient();

$response = $client->request('GET', 'https://api.github.com/user', [
    'headers' => [
        'Authorization' => 'Bearer ' . $_SESSION['github_access_token'],
        'User-Agent' => 'OAuth2 Client'
    ]
]);

$body = $response->getBody();
$userData = json_decode($body, true);

In the above code, we called the GitHub API using the Guzzle HTTP client. We set the Authorization header with the access token to indicate that we have access to this API.

Conclusion

Integrating OAuth 2.0 in PHP is a great way to secure your API. Using thephpleague/oauth2-client package we can obtain an access token from the provider and use that token to call the protected API. Additionally, we can store user data and tokens for future use.

Now you can start integrating OAuth 2.0 to secure your API and protect user data.

The above is the detailed content of How to integrate OAuth 2.0 in PHP to secure API. For more information, please follow other related articles on the PHP Chinese website!

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