Sign in to Laravel apps with third-party accounts like Github

Source: Internet
Author: User
Tags oauth
Laravel's socialite makes it easy to sign in to Larave apps with third-party accounts like Facebook, Twitter, Google, LinkedIn, GitHub, and BitBucket. You can make third-party connections to existing users or as a primary login mechanism. Although some of the steps are given in the official documentation, many friends still don't know how to implement the login function after reading it. Today we take Github as an example, detailing how it's implemented.

1. Installing socialite

Install via Composer command line:

$ composer require Laravel/socialite

Then register it in the config/app.php :

' Providers ' = [    ...    Laravel\socialite\socialiteserviceprovider::class,    ...], ' aliases ' = [    ...    '] Socialite ' = Laravel\socialite\facades\socialite::class,    ...],

Now that socialite is registered with your application, let's set up a certificate.

2. Create a Github app

First, you need to have a Github account, then to "Setting" – "OAuth Applications" – "Developer Applications" – "Register new Application" to create an OAuth Application:

Then fill in the application information:

One of the " Authorization callback URL " We set here as "Http://your-domain-name.com/auth/github/callback", you need to fill in according to your application actually. After creation, you can see the value of the client ID and client Secret on the app's detail page.

3. Service Configuration

Open the config/services.php file where you added the Github authorization information:

' GitHub ' = [    ' client_id ' = ' your-github-app-id ',    ' client_secret ' = ' Your-github-app-secret ', '    redirect ' = ' Http://your-callback-url ',],

Fill in the values for the " client ID " and " client Secret " and " Authorization callback URL " of the app created in the second step. Of course, you can also define three environment variables in the . env file, and then get them through the env () function in config/services.php .

4. Defining routes

Add the following route in routes.php (You can customize it to any name, which is defined directly as the following name for convenience):

Route::get (' Auth/github ', ' auth\authcontroller@redirecttoprovider '); Route::get (' Auth/github/callback ', ' auth\authcontroller@handleprovidercallback ');

Let's complete these methods in the controller.

5. Controller method

Add the following method to the Auth\authcontroller:

Public Function Redirecttoprovider ()    {        return socialite::d River (' GitHub ')->redirect ();    }    Public Function Handleprovidercallback ()    {        try {            $user = socialite::d River (' 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 ' and ' = ' $githubUser->email,            ' github_id ' = = $githubUser->id,            ' avatar ' = $githubUser->avatar        ]);    }

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

6. Database design

We need to modify the users migration to store some Github-specific information. Github will return a lot of information to us, and 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 ();

Since we are here for demonstration purposes, it is possible to make changes directly to the above, and you can design according to your actual needs. The information that Github returns for us is as follows:

7. User Eloquent

Modify the User eloquent Model to be able to store Github information:

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

Let's take a look at how the above code works in detail.

8. Use

Add the following link to the location where you want to sign in, with the destination address pointing to the route Auth/github we added above.

When the user clicks on the button above, it jumps to the Github authorization page, asks the user whether to run the authorization, and when the user allows it, jumps back to Auth/github/callback, which is the "Authorization" that we filled in when we created the app callback URL ".

It then executes the code in the callback function, logs in to the existing user, or creates a new user and logs in.

Now that we have a Laravel authorized user, we can directly use all the methods provided by Auth, such as Auth::check (), Auth:user () and so on. You can also add a logout path to run the Auth::logout () method to exit the login. The subsequent operation can be the same as using Laravel's own authentication system.

This completes all the steps to sign in to the Laravel app with your Github account, and the implementation of other third-party apps is basically 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.