How to use Laravel to implement third-party login function
In recent years, with the continuous development of Internet technology, people have higher and higher requirements for the security and user experience of websites or applications. In order to facilitate user registration and login, third-party account login has become one of the commonly used functions in websites and applications. As a popular PHP framework, Laravel provides a convenient social login authorization function, making it particularly convenient to implement third-party login functions. This article will introduce how to use Laravel to implement the third-party login function, and provide some implementation code for readers' reference.
1. Configure service provider information
In Laravel, we can use the social login authorization package socialite
to implement the third-party login function. socialite
supports a variety of authorized service providers, including Facebook, Google, Twitter, WeChat, etc. Therefore, before using socialite
to implement the third-party login function, we need to configure the service provider information.
Taking GitHub as an example, by creating and authorizing an OAuth application, we can obtain the client ID and client key. The specific acquisition method is as follows:
- Visit the GitHub website and log in to the account.
- Enter GitHub's settings page, select the "Developer settings" tab, click "OAuth Apps", and then select "New OAuth App".
- Fill in the details of the application, including application name, application home page URL, authorization callback URL, etc.
- Submit and create the application. After successful creation, information such as the client ID and client key of the application can be found on the GitHub page.
With this information in hand, we can create a Laravel configuration file named /config/services.php
and add the following content to it:
'github' => [ 'client_id' => env('GITHUB_CLIENT_ID'), 'client_secret' => env('GITHUB_CLIENT_SECRET'), 'redirect' => 'http://localhost:8000/login/github/callback', ],
Among them, github
is the name of the service provider we want to use, client_id
and client_secret
are the customers we obtained when applying for the OAuth application The client ID and client secret, redirect
is the OAuth callback URL, it is the authorization callback URL we filled in when creating the application. Here we set it to localhost:8000/login/github/callback. We will create this route in the routing file later.
2. Create a route
Next, we need to create a route in the routing file of the Laravel application to implement the function of logging in through GitHub. Here, we can use Laravel’s Route
class to create routes.
The first step is to create an authorization redirect route, which is responsible for redirecting users to the GitHub login page. Add the following code in the routing file:
Route::get('login/github', function () { return Socialite::driver('github')->redirect(); });
Among them, Socialite::driver('github')
calls the driver
of the socialite
authorization package Method to obtain the instance of the GitHub service provider. The redirect
method implements the OAuth authorization jump and redirects the user to GitHub's authentication and authorization page.
In the second step, we create an authorization callback route, which is responsible for obtaining the user information returned by the GitHub service provider and processing it. Add the following code in the routing file:
Route::get('login/github/callback', function () { $user = Socialite::driver('github')->user(); // 处理用户信息 });
Among them, Socialite::driver('github')
calls the driver
of the socialite
authorization package Method to obtain the instance of the GitHub service provider. The user
method implements the process of obtaining user information through OAuth authorization. It will obtain the user's information from the GitHub service provider, and the information will be returned in the form of the $user
variable.
After obtaining the $user
variable, we can process the user information. Since the format of user information returned by each third-party service provider is slightly different, we will not go into details here.
3. Create public methods
In order to facilitate management and use, we can create in the
app/Http/Controllers/Auth/LoginController.php controller GitHub
method, for other methods to call.
In this method, we first need to use the Socialite::driver('github')->redirect()
method to redirect the user to the GitHub login page. During the callback process of obtaining user information, we can process the user information in the GitHubCallback
method.
The following is a basic sample code:
<?php namespace AppHttpControllersAuth; use AppHttpControllersController; use Socialite; class LoginController extends Controller { /** * 重定向到GitHub登录页面 * * @return Response */ public function GitHub() { return Socialite::driver('github')->redirect(); } /** * 从GitHub获取用户信息 * * @return Response */ public function GitHubCallback() { $user = Socialite::driver('github')->user(); dd($user); } }
4. Using the expansion package
If you feel that the above method is cumbersome, you can use the social login authorization expansion packagelaravel/socialite
, this extension package has encapsulated major service providers and provided corresponding command line tools to construct authorized service providers.
- Installation
laravel/socialite
Use composer in the terminal to install laravel/socialite
Extension package:
composer require laravel/socialite
- Configuring service provider information
In Laravel’s configuration file config/services.php
, add the service provider information you need to use. Take GitHub as an example below. :
'github' => [ 'client_id' => env('GITHUB_CLIENT_ID'), 'client_secret' => env('GITHUB_CLIENT_SECRET'), 'redirect' => '/auth/github/callback', ],
- Create authorization route
In the routes/web.php
routing file, create an authorization route that is not verified:
Route::get('/auth/github', 'AuthLoginController@GitHub');
- 创建回调路由
在routes/web.php
路由文件中,创建一个授权回调路由:
Route::get('/auth/github/callback', 'AuthLoginController@GitHubCallback');
- 创建控制器
在app/Http/Controllers/Auth
目录下,创建一个名为LoginController.php
的控制器。控制器中添加方法GitHub
和GitHubCallback
实现授权和回调过程,具体代码如下:
use Socialite; class LoginController extends Controller { public function GitHub() { return Socialite::driver('github')->redirect(); } public function GitHubCallback() { $user = Socialite::driver('github')->user(); dd($user); } }
至此,我们已经成功使用laravel/socialite
扩展包实现了第三方登录的功能。
总结:
本文介绍了如何使用Laravel框架的社交化登录授权包socialite
,在实现第三方登录功能方面变得尤为便利。通过配置服务商信息、创建路由以及使用扩展包等方法,我们可以轻松地实现通过GitHub登录的功能。希望这篇文章能够对各位开发人员有所帮助。
The above is the detailed content of How to use Laravel to implement third-party login function. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

What is GateToken(GT) currency? GT (GateToken) is the native asset on the GateChain chain and the official platform currency of Gate.io. The value of GT coins is closely related to the development of Gate.io and GateChain ecology. What is GateChain? GateChain was born in 2018 and is a new generation of high-performance public chain launched by Gate.io. GateChain focuses on protecting the security of users' on-chain assets and providing convenient decentralized transaction services. GateChain's goal is to build an enterprise-level secure and efficient decentralized digital asset storage, distribution and transaction ecosystem. Gatechain has original

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.

Comparing Laravel's Blade and CodeIgniter's Twig template engine, choose based on project needs and personal preferences: Blade is based on MVC syntax, which encourages good code organization and template inheritance. Twig is a third-party library that provides flexible syntax, powerful filters, extended support, and security sandboxing.
