Use a third-party account such as Github to log on to the Laravel application

Source: Internet
Author: User
Tags oauth
Using third-party accounts such as Github to log on to the Laravel application's social networks makes it easy to use third-party accounts such as Facebook, Twitter, Google, LinkedIn, GitHub, and Bitbucket to log on to the Laravel application. You can connect them to an existing user by using a third-party connection or as a primary logon mechanism. Although some steps are provided in the official documentation, many of my friends still do not know how to implement the logon function after reading them. Today, we will take Github as an example to detail its implementation methods.

1. install Societe

Use the Composer command line to install:

$ composer require laravel/socialite

Then register itConfig/app. phpMedium:

'providers' => [    ...    Laravel\Socialite\SocialiteServiceProvider::class,    ...],'aliases' => [    ...    'Socialite' => Laravel\Socialite\Facades\Socialite::class,    ...],

Now that Societe has been registered with your application, set the certificate.

2. create a Github application

First, you need to have a Github account, and then go to "Setting"-"OAuth applications"-"Developer applications"-"Register new application" to create an OAuth application:

Then enter the application information:

"Authorization callback URL"Here we set it to" http://your-domain-name.com/auth/github/callback?, you should fill in your application examples. After the application is created, you can see"Client IDAndClient Secret.

3. service configuration

OpenConfig/services. phpFile to add the Github authorization information:

'github' => [    'client_id' => 'your-github-app-id',    'client_secret' => 'your-github-app-secret',    'redirect' => 'http://your-callback-url',],

Create the"Client IDAndClient Secret"And"Authorization callback URL. Of course, you can also. EnvThe file defines three environment variables, and thenConfig/services. phpIs obtained through the env () function.

4. define a route

InRoutes. phpAdd the following route (you can customize it as any name, which is directly defined as the following name for convenience ):

Route::get('auth/github', 'Auth\AuthController@redirectToProvider');Route::get('auth/github/callback', 'Auth\AuthController@handleProviderCallback');

The following describes the methods in the controller.

5. Controller method

Add the following method to Auth \ AuthController:

public function redirectToProvider()    {        return Socialite::driver('github')->redirect();    }    public function handleProviderCallback()    {        try {            $user = Socialite::driver('github')->user();        } catch (Exception $e) {            return Redirect::to('auth/github');        }        $authUser = $this->findOrCreateUser($user);        Auth::login($authUser, true);        return redirect('/');    }    private function findOrCreateUser($githubUser)    {        if ($authUser = User::where('github_id', $githubUser->id)->first()) {            return $authUser;        }        return User::create([            'name' => $githubUser->name,            'email' => $githubUser->email,            'github_id' => $githubUser->id,            'avatar' => $githubUser->avatar        ]);    }

The above is just a general method of implementation. of course, you can also implement it in your own way. First jump to Github, get user authorization, and then jump back to, then find a user based on the Github ID and log on, or create a new user.

6. database design

We need to modify users Migration to store some specific Github information. Github will return a lot of information for us. here we choose some of them for storage.

$table->increments('id');            $table->string('github_id')->unique();            $table->string('name');            $table->string('email');            $table->string('avatar');            $table->rememberToken();            $table->timestamps();

Because we are here for demonstration, you can directly change it to the above, you can design it according to your actual needs. Github returns the following information:

7. User Eloquent

Modify the User Eloquent Model to store Github information:

protected $fillable = ['name', 'email', 'github_id', 'avatar'];

Let's take a look at how the above code runs.

8. use

Add the following link where you want to log on. the destination address of the link directs to the route auth/github we added above.

When a user clicks the above button, the Github authorization page is displayed, asking the user whether to run the authorization. after the user permits the operation, the user will jump back to auth/github/callback, that is, the "Authorization callback URL" We entered when creating an application ".

Then, the code in the callback function is executed to log on to an existing user, or create a new user and log on.

Now we have a user authorized by Laravel. you can directly use all the methods provided by Auth, such as Auth: check () and Auth: user. You can also add a logout route to run the Auth: logout () method to log out. The subsequent operations will be the same as using Laravel's own authentication system.

All the steps for logging on to the Laravel application using the Github account are completed. the implementation of other third-party applications is similar.

Reference: laravel.com, mattstauffer. co

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.