Laravel 11 Socialite Login with Slack Account

Websolutionstuff | Aug-16-2024 | Categories : Laravel

Hello, laravel web developers! In this article, we'll see how to Socialite login with Slack in laravel 11. In laravel 11, previously saw Socialite login with Google, Facebook, and GitHub account. Slack is a new way to communicate with your team. It's faster, better organized, and more secure than email.

In this example, we will install the Socialite composer package to enable login with a Slack account. Then we will configure Laravel to support Slack authentication. After that, we will add a login with Slack button, allowing users to log in and register using their Slack account

Laravel 11 Socialite Login with Slack Account

laravel 11 socialite login with slack account

 

Step 1: Install Laravel 11 Application

In this step, we'll install the aravel 11 application using the following command.

composer create-project laravel/laravel example-app

 

Step 2: Install Laravel UI

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

composer require laravel/ui

Next, we'll create a basic bootstrap auth using the following command.

php artisan ui bootstrap --auth

Now, install the node.js package using the following command.

npm install

let's run the package using the following command.

npm run build

 

Step 3: Install Socialite

Next, install Laravel Socialite using the following command.

composer require laravel/socialite

 

Step 4: Create Slack App

Now, we'll create a Slack app using the following steps:

Create a Slack App

  • Log in to Slack:

    • Open your web browser and log in to your Slack account.
  • Go to the Slack API Website:

  • Create a New App:

    • Click on the Create New App button.
  • Choose the App's Development Environment:

    • Select "From scratch" to start with a new app.
  • Fill in the App Details:

    • App Name: Enter a name for your application (e.g., "Laravel Socialite App").
    • Development Slack Workspace: Choose the workspace where you want to develop your app.
  • Click Create App:

    • Click on the Create App button.

 

Configure OAuth & Permissions
  1. Navigate to OAuth & Permissions:

    • In the left sidebar, click on OAuth & Permissions.
  2. Add a Redirect URL:

    • In the Redirect URLs section, click on Add a Redirect URL.
    • Enter your redirect URL, which should match the SLACK_REDIRECT_URI in your .env file, typically something like https://your-app-url.com/auth/slack/callback.
    • Click Add and then Save URLs.
  3. Select Scopes:

    • Scroll down to the Scopes section.
    • Add the necessary OAuth scopes. For authentication purposes, you will generally need identity.basic, identity.email, identity.team, and identity.avatar.

 

Install the App to Your Workspace
  1. Navigate to OAuth & Permissions:

    • Still in the OAuth & Permissions page, scroll to the OAuth Tokens & Redirect URLs section.
  2. Install App:

    • Click on the Install App to Workspace button.
    • Authorize the installation.
  3. Get Your Credentials:

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

 

Add Credentials to Your Laravel Project

Open your .env file and add the following lines, replacing the placeholders with your actual Client ID, Client Secret, and Redirect URI:

SLACK_CLIENT_ID=your-slack-client-id
SLACK_CLIENT_SECRET=your-slack-client-secret
SLACK_REDIRECT_URI=https://your-app-url.com/auth/slack/callback

 

Update config/services.php

Make sure your config/services.php file has the Slack configuration.

'slack' => [
    'client_id' => env('SLACK_CLIENT_ID'),
    'client_secret' => env('SLACK_CLIENT_SECRET'),
    'redirect' => env('SLACK_REDIRECT_URI'),
],

 

Step 5: Add slack_id Column

Next, we'll add the slack_id column into the users table.

php artisan make:migration add_slack_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('slack_id')->nullable();
        });
    }

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

Now, run the migration command:

php artisan migrate

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',
        'slack_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

Then, we'll define the routes into the web.php file.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

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

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
  
Route::controller(SlackController::class)->group(function(){
    Route::get('auth/slack', 'redirectToSlack')->name('auth.slack');
    Route::get('auth/slack/callback', 'handleSlackCallback');
});

 

Step 7: Create Controller

Next, we need to implement the redirectToSlack and handleSlackCallback methods in the SlackController.

app/Http/Controllers/SlackController.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 SlackController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToSlack()
    {
        return Socialite::driver('slack')->redirect();
    }
          
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleSlackCallback()
    {
        try {
        
            $user = Socialite::driver('slack')->user();
         
            $findUser = User::where('slack_id', $user->id)->first();
         
            if($findUser){
         
                Auth::login($findUser);
        
                return redirect()->intended('home');
         
            }else{
                $newUser = User::updateOrCreate(['email' => $user->email],[
                        'name' => $user->name,
                        'slack_id'=> $user->id,
                        'password' => encrypt('user123456')
                    ]);
        
                Auth::login($newUser);
        
                return redirect()->intended('home');
            }
        
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

 

Step 8: Update Blade File

We'll add the GitLab login button to our login form.

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.slack') }}" 
                                   style="display: flex; align-items: center; justify-content: center; padding: 10px; 
                                   background-color: #4A154B; color: #FFFFFF; text-decoration: none; border-radius: 4px;">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 2447.6 2452.5" fill="none">
                                        <g clip-path="url(#clip0)">
                                            <path d="M476.2 1226.3C476.2 1030.8 625.9 881.1 821.4 881.1H1096.3V1156C1096.3 1351.4 946.6 1501.1 751.1 1501.1C555.7 1501.1 405.9 1351.4 405.9 1156H251.5C251.5 1408.6 492.4 1649.5 745 1649.5C997.6 1649.5 1238.5 1408.6 1238.5 1156V821.4C1238.5 625.9 1388.2 476.2 1583.6 476.2H1858.5V751.1C1858.5 946.6 1708.8 1096.3 1513.3 1096.3C1317.9 1096.3 1168.1 946.6 1168.1 751.1H1013.7C1013.7 1030.8 1262.6 1279.7 1542.3 1279.7C1822.1 1279.7 2071 1030.8 2071 751.1V405.9C2071 207.1 1884.8 20.9 1686 20.9H1411.1C1215.6 20.9 1065.9 170.6 1065.9 366.1V641C1065.9 836.5 915.2 986.2 719.7 986.2C524.3 986.2 374.5 836.5 374.5 641H220.1C220.1 1030.8 478.6 1226.3 751.1 1226.3H476.2Z" fill="#36C5F0"/>
                                            <path d="M1226.3 476.2C1226.3 671.6 1076.6 821.4 881.1 821.4H476.2V476.2C476.2 280.7 625.9 130.9 821.4 130.9H1226.3V476.2Z" fill="#2EB67D"/>
                                            <path d="M1076.6 1226.3C1076.6 1421.8 1226.3 1571.5 1421.8 1571.5H1858.5V1226.3H1421.8C1226.3 1226.3 1076.6 1376 1076.6 1571.5Z" fill="#ECB22E"/>
                                            <path d="M1226.3 1858.5C1226.3 2065.3 1376 2214.9 1582.8 2214.9H1858.5V1858.5H1582.8C1387.3 1858.5 1226.3 2009.5 1226.3 2214.9Z" fill="#E01E5A"/>
                                        </g>
                                        <defs>
                                            <clipPath id="clip0">
                                                <rect width="2447.6" height="2452.5" fill="white"/>
                                            </clipPath>
                                        </defs>
                                    </svg>
                                    <span style="margin-left: 10px;">Login with Slack</span>
                                </a>

                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

Step 9: Run the 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 Get Element By Data Attribute In jQuery
How To Get Element By Data Att...

In this article, we'll learn how to locate elements using data-attribute values. We can do this using jQuery and CSS...

Read More

Jul-11-2022

How to Validate Empty Input Field in jQuery
How to Validate Empty Input Fi...

In the dynamic world of web development, form validation is a crucial aspect of creating a user-friendly and error-free...

Read More

Sep-25-2023

How To Create Zip File In Laravel 7/8
How To Create Zip File In Lara...

In this tutorial I will give you example of how to create zip file in laravel 7/8. Some times client's have requirme...

Read More

Dec-17-2021

Laravel 9 CRUD With Image Upload Example
Laravel 9 CRUD With Image Uplo...

In this article, we will see the laravel 9 crud with an image upload example. Here, we will learn how to image upload wi...

Read More

Dec-09-2022