Laravel 11 Socialite Login with Gitlab Account

Websolutionstuff | Aug-14-2024 | Categories : Laravel

Hello, Laravel web developers! In this article, I'll show you how to log in with GitLab in Laravel 11 using Socialite. GitLab is a comprehensive AI-powered DevSecOps platform, and integrating it into your Laravel application for authentication is a great way to streamline user management.

We'll create a form and add a GitLab social login button, making it easy for users to log in using their GitLab accounts. Let's get started!

Laravel 11 Socialite Login with GitLab Account

laravel 11 socialite login with gitlab account

 

Step 1: Install Laravel 11 Application

In this step, we'll install laravel 11 application using the following code.

composer create-project laravel/laravel example-app

 

Step 2: Install Laravel UI

Then, we'll install laravel UI using the following command.

composer require laravel/ui

Next, we'll create basic login and register using laravel auth command.

php artisan ui bootstrap --auth

Then, install node js package.

npm install

Now, run the npm package using the following command.

npm run build

 

Step 3: Install Socialite

Next, we'll install the Laravel Socialite package. Open your terminal and run the following command.

composer require laravel/socialite

 

Step 4: Create Gitlab App

Then, we'll create a GitLab application and get the credentials. Click here to create a account in https://developer.gitlab.com/

  • Log in to GitLab:

    • Open your web browser and log in to your GitLab account.
  • Navigate to the Applications Page:

    • In the top-right corner, click on your avatar and select Settings.
    • In the left sidebar, click on Applications.
  • Register a New Application:

    • Click the New application button.
  • Fill in the Application Details:

    • Name: Enter a name for your application (e.g., "Laravel Socialite App").
    • Redirect URI: Add the callback URL that GitLab will redirect to after authentication. This should match the GITLAB_REDIRECT_URI in your .env file, typically something like http://localhost:8000/auth/gitlab/callback.
    • Scopes: Select the scopes that your application requires. For authentication purposes, you will generally need the read_useropenid, profile, and email scopes.
  • Save the Application:

    • Click the Save application button.
  • Get Your Credentials:

    • After saving, GitLab will provide you with a Client ID and a Client Secret. Copy these values.

Next, we need to set up Socialite to use GitLab. Open the config/services.php file and add the following configuration.

config/services.php

'gitlab' => [
    'client_id' => env('GITLAB_CLIENT_ID'),
    'client_secret' => env('GITLAB_CLIENT_SECRET'),
    'redirect' => env('GITLAB_REDIRECT_URI'),
],

Then, add your GitLab credentials to your .env file.

GITLAB_CLIENT_ID=your-gitlab-client-id
GITLAB_CLIENT_SECRET=your-gitlab-client-secret
GITLAB_REDIRECT_URI=https://your-app-url.com/auth/gitlab/callback

 

Step 5: Add gitlab_id Column

Next, we'll add GitLab ID column into users table. So, create a migration using the following command.

php artisan make:migration add_gitlab_id_column

Migration

<?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 ($table) {
            $table->string('gitlab_id')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        //
    }
};

Then, migrate the table into the database using the following command.

php artisan migrate

Then, update the User.php model.

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'gitlab_id'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}

 

Step 6: Define Routes

Now, let's create the routes for GitLab authentication. Open the routes/web.php file and add the following routes.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\GitLabController;
  
Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
  
Route::controller(GitLabController::class)->group(function(){
    Route::get('auth/gitlab', 'redirectToGitlab')->name('auth.gitlab');
    Route::get('auth/gitlab/callback', 'handleGitlabCallback');
});

 

Step 7: Create Controller

Next, we need to implement the redirectToGitLab and handleGitLabCallback methods in the GitLabController.

app/Http/Controllers/GitLabController.php

<?php
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
    
class GitLabController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGitlab()
    {
        return Socialite::driver('gitlab')->redirect();
    }
          
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleGitlabCallback()
    {
        try {
        
            $user = Socialite::driver('gitlab')->user();         
            $findUser = User::where('gitlab_id', $user->id)->first();
         
            if($findUser){         

                Auth::login($findUser);        
                return redirect()->intended('home');
         
            }else{
                $newUser = User::updateOrCreate(['email' => $user->email],[
                        'name' => $user->name,
                        'gitlab_id'=> $user->id,
                        'password' => encrypt('123456dummy')
                    ]);
        
                Auth::login($newUser);
        
                return redirect()->intended('home');
            }
        
        } catch (Exception $e) {
            info($e->getMessage());
        }
    }
}

 

Step 8: Update Blade File

Next, we'll to add the GitLab login button to our login form. Open your resources/views/auth/login.blade.php file and add the following button.

resources/views/auth/login.blade.php

@extends('layouts.app')

@section('content')
<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">
                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                        <div class="row mb-3">
                            <label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>

                                @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">

                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6 offset-md-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>

                                    <label class="form-check-label" for="remember">
                                        {{ __('Remember Me') }}
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))
                                    <a class="btn btn-link" href="{{ route('password.request') }}">
                                        {{ __('Forgot Your Password?') }}
                                    </a>
                                @endif
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-6 offset-md-4 mt-2">
                               <a class="btn btn-dark" href="{{ route('auth.gitlab') }}" style="display: flex; align-items: center; justify-content: center; padding: 10px; background-color: #FC6D26; color: #FFFFFF; text-decoration: none; border-radius: 4px;">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
                                        <path fill="#E24329" d="M11.996 22.858L16.528 8.956H7.469L11.996 22.858Z"/>
                                        <path fill="#FC6D26" d="M11.996 22.858L7.469 8.956H2.85L11.996 22.858Z"/>
                                        <path fill="#FCA326" d="M2.85 8.956L0.631 14.845C0.42 15.433 0.495 16.099 0.838 16.628L11.996 22.858L2.85 8.956Z"/>
                                        <path fill="#FC6D26" d="M2.85 8.956H7.469L3.124 2.768C2.845 2.321 2.251 2.316 1.968 2.764L2.85 8.956Z"/>
                                        <path fill="#E24329" d="M11.996 22.858L16.528 8.956H21.147L11.996 22.858Z"/>
                                        <path fill="#FC6D26" d="M21.147 8.956H16.528L20.872 2.768C21.151 2.321 21.745 2.316 22.028 2.764L21.147 8.956Z"/>
                                        <path fill="#FCA326" d="M23.366 14.845L21.147 8.956H16.528L20.872 15.845C21.091 16.292 21.685 16.297 21.968 15.849L23.366 14.845Z"/>
                                    </svg>
                                    <span style="margin-left: 10px;">Login with GitLab</span>
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

Step 9: Run Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

Recommended Post
Featured Post
How To Generate QRcode In Laravel
How To Generate QRcode In Lara...

In this example, I will give information about how to generate QR code in laravel. As per the current trend, many w...

Read More

Jun-01-2020

How To Merge Two Collections In Laravel
How To Merge Two Collections I...

In this article, we will see how to merge two collections in laravel 8 or laravel 9. The Illuminate\Support\Co...

Read More

Jul-18-2022

How To Validate Email Using jQuery
How To Validate Email Using jQ...

In this article, we will see how to validate email using jquery. we will use regular expression(regex) for email va...

Read More

Nov-09-2022

Send Mail Example In Laravel 8
Send Mail Example In Laravel 8

In this article, we will see send mail in laravel 8. here we will see how to send mail in laravel 8. Emai...

Read More

Oct-16-2020