Home  >  Article  >  Backend Development  >  Implement third-party login and authorization using PHP and OAuth2

Implement third-party login and authorization using PHP and OAuth2

PHPz
PHPzOriginal
2023-06-25 18:33:22984browse

With the continuous development and popularization of the Internet, more and more websites and applications will provide third-party login and authorization services to facilitate users to quickly register and log in, and also to obtain user data more conveniently. As a common open authorization standard, OAuth2 is widely used in third-party login and authorization scenarios.

This article will introduce how to use PHP and OAuth2 to implement third-party login and authorization. We will use GitHub as an example platform to demonstrate how to use OAuth2 to obtain user information and store this information in a local database.

1. First, you need to create an OAuth application on GitHub

Create an OAuth application on GitHub, and record the generated client ID and client secret for subsequent use.

2. Install the OAuth2 client library

You can use a third-party OAuth2 client library to implement OAuth2 in PHP. Here we use thephpleague/oauth2-client as a sample library.

Use Composer to install. If you haven't installed Composer yet, please install it first.

Execute the following command in the terminal:

composer require league/oauth2-client

3. Build the authorization link

Building the authorization link is the first step. Using the authorization link, the user can be redirected to GitHub and request authorization.

The following is a sample code to build an authorization link:

<?php

require_once __DIR__ . '/vendor/autoload.php';

$provider = new LeagueOAuth2ClientProviderGithub([
    'clientId'          => 'YOUR_CLIENT_ID',
    'clientSecret'      => 'YOUR_CLIENT_SECRET',
    'redirectUri'       => 'http://localhost:8000/callback.php',
]);

$authUrl = $provider->getAuthorizationUrl([
    'scope' => ['user'],
]);

header('Location: ' . $authUrl);

This code does the following things:

  1. Creates a GitHub provider instance, provides Obtain the required OAuth application information
  2. Use the getAuthorizationUrl method to get the authorization link and redirect the user to this link

4. Process the callback URL and obtain the access token

Once the user authorizes your app on GitHub, they will be redirected back to your app. In this redirect URL you can get the access token.

Here is the sample code to get the access token:

<?php

require_once __DIR__ . '/vendor/autoload.php';

$provider = new LeagueOAuth2ClientProviderGithub([
    'clientId'          => 'YOUR_CLIENT_ID',
    'clientSecret'      => 'YOUR_CLIENT_SECRET',
    'redirectUri'       => 'http://localhost:8000/callback.php',
]);

if (!isset($_GET['code'])) {
    die('授权失败:没有授权码!');
} else {
    $accessToken = $provider->getAccessToken('authorization_code', [
        'code' => $_GET['code'],
    ]);
}

echo '访问令牌:' . $accessToken->getToken();

5. Get user data and store

Now that we have obtained the access token, we can use the access token to obtain user data. Take obtaining user information as an example:

$user = $provider->getResourceOwner($accessToken);

echo '用户ID:' . $user->getId() . '<br>';
echo '用户名:' . $user->getNickname() . '<br>';
echo '头像URL:' . $user->getAvatarUrl() . '<br>';
echo '主页URL:' . $user->getProfileUrl() . '<br>';

After obtaining user data, we can store the data in the local database for future use.

6. Summary

In this article, we introduced how to use PHP and OAuth2 to implement third-party login and authorization. Through a simple example, we learned how to use the OAuth2 client library to build authorization links, obtain access tokens, and obtain user data. Hope this article is helpful to you.

The above is the detailed content of Implement third-party login and authorization using PHP and OAuth2. 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