国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home PHP Framework Laravel Laravel development: How to quickly integrate third-party login using Laravel Socialite?

Laravel development: How to quickly integrate third-party login using Laravel Socialite?

Jun 13, 2023 pm 10:09 PM
laravel Sign in with socialite

Laravel is a popular PHP framework used for developing web applications. One of the most common features is the integration of third-party logins into the application. Doing so can provide users with a better user experience and reduce repetitive registration processes.

In this article, we will discuss how to integrate third-party login using Laravel Socialite library.

What is Laravel Socialite?

Laravel Socialite is an extension package for the Laravel framework that allows developers to easily implement third-party logins in their applications. It supports various social platforms such as Facebook, Twitter, LinkedIn, etc.

How does Socialite work?

Socialite follows the OAuth protocol. OAuth is an authorization framework that allows users to pass their account information from one site to another without sharing their credentials. OAuth requires user authorization, in which case the user authorizes the application to access their social media accounts.

Socialite authorization works as follows:

  1. The user clicks the "Login" button, which will point to Socialite authorization:

    Route::get('auth/{provider}', 'AuthSocialController@redirectToProvider');
  2. Socialite challenges the user to authorize access to their social media account; Socialite will redirect to the social media site;

    Route::get('auth/{provider}/callback', 'AuthSocialController@handleProviderCallback');

3. The user authorizes their account and the social media site redirects to the callback URL;

public function redirectToProvider($provider)
{
  return Socialite::driver($provider)->redirect();
}
  1. Socialite will return the callback URL with the authorization code to the application, and the application will request the OAuth access token with the authorization code;

    public function handleProviderCallback($provider)
    {
    $socialUser = Socialite::driver($provider)->user();
    }
  2. Upon completion of authentication, Socialite will return the user's authorized token and pass it to the application.

How to use Socialite in Laravel?

Using any social media platform supported by Socialite, you will need to set up application credentials or keys in two places:

    'facebook' => [
        'client_id' => env('FB_CLIENT_ID'),
        'client_secret' => env('FB_CLIENT_SECRET'),
        'redirect' => env('FB_CALLBACK_URL'),
    ]

    'twitter' => [
        'client_id' => env('TW_CLIENT_ID'),
        'client_secret' => env('TW_CLIENT_SECRET'),
        'redirect' => env('TW_CALLBACK_URL'),
    ],

    'google' => [
         'client_id' => env('GOOGLE_CLIENT_ID'),
         'client_secret' => env('GOOGLE_CLIENT_SECRET'),
         'redirect' => env('GOOGLE_CALLBACK_URL')
    ]

Application credentials or keys are intended to authenticate the application's identity .

We will set this in the config/services.php file.

Step 1: Create Authorization Routes

Create the routes used to trigger Socialite authorization:

Route::get('auth/{provider}', 'AuthSocialController@redirectToProvider');
Route::get('auth/{provider}/callback', 'AuthSocialController@handleProviderCallback');

Typically these routes are placed in a controller called SocialController, which Controller is used to handle Socialite authorization and callbacks.

Step 2: Create a SocialController

Like all controllers, we need to create a SocialController that uses good coding practices.

Use the following command to create the controller:

php artisan make:controller AuthSocialController

Ultimately this will allow us to use the authorization provider for authorization and callbacks to our routes.

In SocialController, we define two methods, redirectToProvider and handleProviderCallback. The first is a redirect to the authorization provider. The subsequent callback function then provides the callback URL for the client with the authorization code to retrieve the information and complete the authentication.

The following is a sample code for SocialController:

namespace AppHttpControllersAuth;
use AppHttpControllersController;
use IlluminateSupportFacadesAuth;
use IlluminateHttpRequest;
use LaravelSocialiteFacadesSocialite;

class SocialController extends Controller
{
    /**
     * Redirect the user to the OAuth Provider.
     *
     * @return IlluminateHttpResponse
     */
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }
    /**
     * Obtain the user information from OAuth Provider.
     *
     * @return IlluminateHttpResponse
     */
    public function handleProviderCallback($provider)
    {
        $user = Socialite::driver($provider)->user();

        // Do something with user data, for example:
        // $user->token;
        // $user->getId();
        // $user->getEmail();
    }
}

Step 3: Using a view controller

Normally, we will use a view controller to manage the rendering of all our views. This makes our code easier to read and manage. Let’s create a simple view for our application using Laravel’s view controller.

Use the following command to create the view controller:

php artisan make:controller SocialAuthController

The following are the changes made in the controller.

namespace AppHttpControllers;

use IlluminateHttpRequest;

class SocialAuthController extends Controller
{
    /**
     * Redirect the user to the OAuth Provider.
     *
     * @return IlluminateHttpResponse
     */
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }

    /**
     * Obtain the user information from OAuth Provider.
     *
     * @return IlluminateHttpResponse
     */
    public function handleProviderCallback($provider)
    {
        $user = Socialite::driver($provider)->user();
        $existingUser = User::where('email', $user->getEmail())->first();
        if ($existingUser) { // If user already exists, login the user                
            auth()->login($existingUser, true);
        } else { // Register new user                    
            $newUser = new User();
            $newUser->name = $user->getName();
            $newUser->email = $user->getEmail();
            $newUser->google_id = $user->getId();
            $newUser->password = encrypt('amitthakur');
            $newUser->save();
            auth()->login($newUser, true);
        }
        return redirect()->to('/home');
    }
}

Step 4: Create the login view

Now our controller and routing are ready. Now we need to create the view for login.

Create a view file and name it social_login.blade.php. We need to display buttons that can trigger third-party logins. In this case we will show 3 buttons to support login with Google, Facebook and Twitter.

The following is the sample code for the view file:

@extends('layouts.app')
@section('content')
<main class="py-4">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">{{ __('Login') }}</div>
                    <div class="card-body">
                        <a href="{{ route('social.oauth', ['provider' => 'google']) }}" class="btn btn-google">Sign in with google</a>
                        <a href="{{ route('social.oauth', ['provider' => 'facebook']) }}" class="btn btn-facebook">Sign in with Facebook</a>
                        <a href="{{ route('social.oauth', ['provider' => 'twitter']) }}" class="btn btn-twitter">Sign in with twitter</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>
@endsection

Use the layout file at the top. When the user clicks on any button, we redirect them to the authorization provider. In SocialController respond we will get user data and complete authentication.

Step 5: Create a new route

Now we need to create a new route to handle the above view file.

Modify the web.php file as follows:

Route::get('social', 'SocialAuthController@index')->name('social.login');
Route::get('social/{provider}', 'SocialAuthController@redirectToProvider')->name('social.oauth');
Route::get('social/{provider}/callback', 'SocialAuthController@handleProviderCallback');

We should note that the routes above are identified by name so that they can be referenced in the controller code.

Step 6: Test

Now that we have our social media identities set up, before we can test the application, we need to configure our application through the .env file.

To configure the .env file, add the following code:

FACEBOOK_CLIENT_ID=xxxxxxxxxxxxxxxxx
FACEBOOK_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxx
FACEBOOK_CALLBACK_URL=http://www.example.com/auth/facebook/callback

GOOGLE_CLIENT_ID=xxxxxxxxxxxxxxxxx
GOOGLE_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxx
GOOGLE_CALLBACK_URL=http://www.example.com/auth/google/callback

TWITTER_CLIENT_ID=xxxxxxxxxxxxxxxxx
TWITTER_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxx
TWITTER_CALLBACK_URL=http://www.example.com/auth/twitter/callback

Replace the actual application ID with "xxxxxxxxxxxxxxxxxxxx" in this line. Afterwards, we can launch our application via the command line and access the view file above. Once we click any button and authorize our account via OAuth, we are authenticated with every known user.

Conclusion

In this article, we learned how to integrate third-party login using Laravel Socialite library. The main purpose of Socialite is to simplify the social media login process to improve user experience. We learned how to set up Socialite to support Google, Facebook, and Twitter. We also retrieve the authorization code in the controller and complete the OAuth authentication using the requested data. The process will actually create a new account or update an existing account.

The above is the detailed content of Laravel development: How to quickly integrate third-party login using Laravel Socialite?. 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
1502
276
How to set environment variables in PHP environment Description of adding PHP running environment variables How to set environment variables in PHP environment Description of adding PHP running environment variables Jul 25, 2025 pm 08:33 PM

There are three main ways to set environment variables in PHP: 1. Global configuration through php.ini; 2. Passed through a web server (such as SetEnv of Apache or fastcgi_param of Nginx); 3. Use putenv() function in PHP scripts. Among them, php.ini is suitable for global and infrequently changing configurations, web server configuration is suitable for scenarios that need to be isolated, and putenv() is suitable for temporary variables. Persistence policies include configuration files (such as php.ini or web server configuration), .env files are loaded with dotenv library, and dynamic injection of variables in CI/CD processes. Security management sensitive information should be avoided hard-coded, and it is recommended to use.en

What is Configuration Caching in Laravel? What is Configuration Caching in Laravel? Jul 27, 2025 am 03:54 AM

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

How to make PHP container support automatic construction? Continuously integrated CI configuration method of PHP environment How to make PHP container support automatic construction? Continuously integrated CI configuration method of PHP environment Jul 25, 2025 pm 08:54 PM

To enable PHP containers to support automatic construction, the core lies in configuring the continuous integration (CI) process. 1. Use Dockerfile to define the PHP environment, including basic image, extension installation, dependency management and permission settings; 2. Configure CI/CD tools such as GitLabCI, and define the build, test and deployment stages through the .gitlab-ci.yml file to achieve automatic construction, testing and deployment; 3. Integrate test frameworks such as PHPUnit to ensure that tests are automatically run after code changes; 4. Use automated deployment strategies such as Kubernetes to define deployment configuration through the deployment.yaml file; 5. Optimize Dockerfile and adopt multi-stage construction

Explain Laravel Eloquent Scopes. Explain Laravel Eloquent Scopes. Jul 26, 2025 am 07:22 AM

Laravel's EloquentScopes is a tool that encapsulates common query logic, divided into local scope and global scope. 1. The local scope is defined with a method starting with scope and needs to be called explicitly, such as Post::published(); 2. The global scope is automatically applied to all queries, often used for soft deletion or multi-tenant systems, and the Scope interface needs to be implemented and registered in the model; 3. The scope can be equipped with parameters, such as filtering articles by year or month, and corresponding parameters are passed in when calling; 4. Pay attention to naming specifications, chain calls, temporary disabling and combination expansion when using to improve code clarity and reusability.

PHP development user permission management monetization PHP permission control and role management PHP development user permission management monetization PHP permission control and role management Jul 25, 2025 pm 06:51 PM

User permission management is the core mechanism for realizing product monetization in PHP development. It separates users, roles and permissions through a role-based access control (RBAC) model to achieve flexible permission allocation and management. The specific steps include: 1. Design three tables of users, roles, and permissions and two intermediate tables of user_roles and role_permissions; 2. Implement permission checking methods in the code such as $user->can('edit_post'); 3. Use cache to improve performance; 4. Use permission control to realize product function layering and differentiated services, thereby supporting membership system and pricing strategies; 5. Avoid the permission granularity is too coarse or too fine, and use "investment"

How to create a helper file in Laravel? How to create a helper file in Laravel? Jul 26, 2025 am 08:58 AM

Createahelpers.phpfileinapp/HelperswithcustomfunctionslikeformatPrice,isActiveRoute,andisAdmin.2.Addthefiletothe"files"sectionofcomposer.jsonunderautoload.3.Runcomposerdump-autoloadtomakethefunctionsgloballyavailable.4.Usethehelperfunctions

How to build a log management system with PHP PHP log collection and analysis tool How to build a log management system with PHP PHP log collection and analysis tool Jul 25, 2025 pm 08:48 PM

Select logging method: In the early stage, you can use the built-in error_log() for PHP. After the project is expanded, be sure to switch to mature libraries such as Monolog, support multiple handlers and log levels, and ensure that the log contains timestamps, levels, file line numbers and error details; 2. Design storage structure: A small amount of logs can be stored in files, and if there is a large number of logs, select a database if there is a large number of analysis. Use MySQL/PostgreSQL to structured data. Elasticsearch Kibana is recommended for semi-structured/unstructured. At the same time, it is formulated for backup and regular cleaning strategies; 3. Development and analysis interface: It should have search, filtering, aggregation, and visualization functions. It can be directly integrated into Kibana, or use the PHP framework chart library to develop self-development, focusing on the simplicity and ease of interface.

How to implement a referral system in Laravel? How to implement a referral system in Laravel? Aug 02, 2025 am 06:55 AM

Create referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,

See all articles