亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Backend Development PHP Tutorial Implementing & testing Socialite authentication in Laravel

Implementing & testing Socialite authentication in Laravel

Jan 03, 2025 am 11:17 AM

Implementing & testing Socialite authentication in Laravel

Laravel Socialite is a first-party Laravel package that helps developers implement OAuth & OAuth2 social authentication in their applications. It has built-in support for Facebook, Twitter, Google, LinkedIn, GitHub, GitLab, and Bitbucket. Socialite can support other providers through community packages.

This post will:

  • Explain what Socialite does and does not do.
  • Show how to integrate Google authentication into a new Laravel project via Socialite.
  • Show an example of testing Socialite.

TLDR: you can view the completed project on my GitHub. Take a look at it if you would rather just read the completed code.

What does Laravel Socialite do and not do?

Socialite is a small package, with its main API primarily consisting of two main methods:

  • Socialite::driver($authProvider)->redirect() will redirect the user to the specified auth provider, passing any necessary information to the provider via URL parameters.
  • Socialite::driver($authProvider)->user() retrieves user data passed back from the auth provider and makes it available to the endpoint.

There are additional support methods for settings scopes and optional parameters. You can read about them in the Socialite documentation.

Socialite does not do the following: it leaves the implementation of these features up to the developer:

  • ? Create database tables or columns needed to store social auth data.
  • ? Create users that don't exist during the authentication process.
  • ? Authenticate the user after a successful OAuth flow.
  • ? Refresh OAuth tokens.

Prerequisites: creating a Google Cloud project

We will set up a small Socialite project that allows the user to authenticate via Google. To do that, you must create a Google app.

First create a new Google Cloud project, then configure an OAuth consent screen for the project. Set the user type to external, then enable the following scopes:

  • .../auth/userinfo.email
  • .../auth/userinfo.profile

After configuring the consent screen, create an OAuth 2.0 Client ID by visiting the Google Cloud Credentials Page. Hold on to the client ID and client secret: we will use them later in the project.

Setting up a minimal Laravel project with Socialite

Create a new Laravel project:

laravel new socialite-tests

Select the following options from the installer:

 ┌ Would you like to install a starter kit? ────────────────────┐
 │ No starter kit                                               │
 └──────────────────────────────────────────────────────────────┘

 ┌ Which testing framework do you prefer? ──────────────────────┐
 │ Pest                                                         │
 └──────────────────────────────────────────────────────────────┘

 ┌ Which database will your application use? ───────────────────┐
 │ SQLite                                                       │
 └──────────────────────────────────────────────────────────────┘

 ┌ Would you like to run the default database migrations? ──────┐
 │ Yes                                                          │
 └──────────────────────────────────────────────────────────────┘

Change into the project directory and install Socialite.

laravel new socialite-tests

Create a new migration.

 ┌ Would you like to install a starter kit? ────────────────────┐
 │ No starter kit                                               │
 └──────────────────────────────────────────────────────────────┘

 ┌ Which testing framework do you prefer? ──────────────────────┐
 │ Pest                                                         │
 └──────────────────────────────────────────────────────────────┘

 ┌ Which database will your application use? ───────────────────┐
 │ SQLite                                                       │
 └──────────────────────────────────────────────────────────────┘

 ┌ Would you like to run the default database migrations? ──────┐
 │ Yes                                                          │
 └──────────────────────────────────────────────────────────────┘

Place the following code in the newly created migration file in database/migrations:

cd socialite-tests
composer require laravel/socialite

This migration adds fields that will be provided by Socialite when the user successfully authenticates. In our implementation we're adding these fields directly onto the user table for simplicity. If you wanted to support more providers than Google, you may want to create a separate table that could store multiple providers per user.

We're setting the password to be nullable because a user will never set a password if they only authenticate via Google. If your app permits social authentication and password authentication, you must validate that the password is not blank or null when a user attempts to login via a password.

Run the migration.

php artisan make:migration add_socialite_fields_to_users

In config/services.php, add the following block of code to the end of the services array. You can find a full list of valid Socialite service names in the configuration docs.

<?php
// database/migrations/2024_12_31_075619_add_socialite_fields_to_users.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('google_id')->default('');
            $table->string('google_token')->default('');
            $table->string('google_refresh_token')->default('');

            // If your app allows both password and social logins, you
            // MUST validate that the password is not blank during login.
            // If you do not, an attacker could gain access to an account
            // that uses social login by only knowing the email.
            $table->string('password')->nullable()->change();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('google_id');
            $table->dropColumn('google_token');
            $table->dropColumn('google_refresh_token');
            $table->string('password')->nullable(false)->change();
        });
    }
};

Add the following to .env, using the credentials from your Google app that you created in the "prerequisites" section.

php artisan migrate

Replace the contents of routes/web.php with the following code.

// config/services.php

'google' => [
    'client_id' => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect' => '/auth/google/callback',
],

The new code in this file implements the routes for:

  • Redirecting to Google for social login with the appropriate information.
  • Handling the callback from Google. This route creates or updates a user upon login, then authenticates them, and redirects them to the homepage.
  • Logging out an authenticated user.

Finally, replace the contents of resources/views/welcome.php with the following markup.

# .env

GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"

With this completed, we can manually test the app by running the development server.

<?php
// routes/web.php

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Laravel\Socialite\Facades\Socialite;
use Laravel\Socialite\Two\InvalidStateException;
use Laravel\Socialite\Two\User as OAuth2User;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/auth/google/redirect', function () {
    return Socialite::driver('google')->redirect();
});

Route::get('/auth/google/callback', function () {
    try {
        /** @var OAuth2User $google_user */
        $google_user = Socialite::driver('google')->user();
    } catch (InvalidStateException $exception) {
        abort(400, $exception->getMessage());
    }

    $user = User::updateOrCreate([
        'email' => $google_user->email,
    ], [
        'google_id' => $google_user->id,
        'name' => $google_user->name,
        'google_token' => $google_user->token,
        'google_refresh_token' => $google_user->refreshToken,
    ]);

    Auth::login($user);
    return redirect('/');
});

Route::get('/auth/logout', function () {
    Auth::logout();
    return redirect('/');
});

When you click the Login with Google link, you should go through the OAuth2 flow and be redirected to the homepage where you can see information about the newly created user from Google.

Testing Socialite with Pest

Our manual tests work, but we'd like automated tests to verify that we don't accidentally break this functionality in the future.

We can create a new test file with the following command.

<!-- resources/views/welcome.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel Socialite Testing Example</title>
</head>
<body>
    <h1>Laravel Socialite Testing Example</h1>
    @if (auth()->check())
        <p>User is authenticated.</p>
        <p>Name: {{ auth()->user()->name }}</p>
        <p>Email: {{ auth()->user()->email }}</p>
        <p><a href="/auth/logout">Logout</a></p>
    @else
        <p>User is not authenticated.</p>
        <p>
            <a href="/auth/google/redirect">Login with Google</a>
        </p>
    @endif
</body>
</html>

Replace the contents of the newly created tests/Feature/AuthRoutesTest.php with the following.

php artisan serve

How the tests work

When testing the redirect route, we test that Socialite redirects to the correct URL and passes the correct URL parameters.

When testing the callback routes, we mock Socialite. Mocking isn't my favorite option: in an ideal world, we could swap out Socialite for another OAuth2 implementation and our tests would still work. However, there's not a straight forward way to hook into the authorization grant request that Socialite sends to garnish the access token. Because of this, mocking is the most practical approach to testing Socialite.

Fluent APIs are tedious to mock via Mockery: you must start from the end call and work your way backwards.

Here is the Socialite method that our callback endpoint invokes.

laravel new socialite-tests

Here is how that must be mocked via Mockery:

 ┌ Would you like to install a starter kit? ────────────────────┐
 │ No starter kit                                               │
 └──────────────────────────────────────────────────────────────┘

 ┌ Which testing framework do you prefer? ──────────────────────┐
 │ Pest                                                         │
 └──────────────────────────────────────────────────────────────┘

 ┌ Which database will your application use? ───────────────────┐
 │ SQLite                                                       │
 └──────────────────────────────────────────────────────────────┘

 ┌ Would you like to run the default database migrations? ──────┐
 │ Yes                                                          │
 └──────────────────────────────────────────────────────────────┘

Finally, we have a test to ensure that navigating directly to the callback URL outside of the OAuth flow returns a 400 status code. We wrapped the call to Socialite::driver('google')->user() in the callback endpoint within a try/catch block. If we hadn't wrapped the Socialite call in a try/catch block and someone typed the callback URL into their browser, the endpoint would throw an exception with an HTTP 500 status code. If your team has monitoring set up for 500 status codes, that could cause someone to get paged in the middle of the night.

Wrapping up

This is a minimal integration, and there's a lot more that could be implemented. If we were implementing an integration with a social provider where the user's email could change, this implementation wouldn't work since it matches against the email address. If the user could change their email address within our app, this implementation also wouldn't work for the same reason. However, now that you've seen how to test Socialite, you could write tests for these scenarios and modify the underlying implementation so that they pass.

I read a lot of blog articles and forum posts about Socialite before I understood how to build my own implementation, how to test it, and what I should think about. I'd like to acknowledge some of those here.

  • How I write integration tests for Laravel Socialite powered apps by Stefan Zweifel
  • ServerSideUp forum: Socialite Best Practices, a conversation
  • Stack Overflow: How to Test Laravel Socialite
  • Stack Exchange: To Link or Not to Link Social Logins with a Matching Email
  • Stack Exchange: Dealing with Connected Social Accounts and Potential Orphans

Read those if you're interested in digging deeper. Also, let me know if you'd be interested in a part 2 of this post where I dig into handling multiple social providers, handling when a user changes their email address, or handling refresh tokens.

The above is the detailed content of Implementing & testing Socialite authentication in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

See all articles