Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Gateway API
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Laravel/Azure] Login with Azure account on Laravel

Posted on October 28, 2025October 28, 2025 By nim No Comments on [Laravel/Azure] Login with Azure account on Laravel

Contents

Toggle
  • Packages
  • Azure App Registration
  • Routes 
  • Add azure_id to users
  • Controller
  • Create the Login Page View

Packages

Cài đặt và Cấu hình các Package Laravel

Install Laravel Socialite:

composer require laravel/socialite

Install the Azure Socialite Provider:

composer require socialiteproviders/microsoft-azure

Add Environment Variables:
Mở tệp .env của bạn và thêm thông tin xác thực bạn đã lấy từ Azure:

AZURE_CLIENT_ID="your-application-client-id"
AZURE_CLIENT_SECRET="your-client-secret-value"
AZURE_TENANT_ID="your-directory-tenant-id"
AZURE_REDIRECT_URI="http://localhost:8000/auth/callback"

Sau đó run:

php artisan config:clear && php artisan cache:clear

Configure Services

In your config/services.php file, add the configuration for the Azure provider :

'azure' => [
    'client_id'     => env('AZURE_CLIENT_ID'),
    'client_secret' => env('AZURE_CLIENT_SECRET'),
    'redirect'      => env('AZURE_REDIRECT_URI'),
    'tenant'        => env('AZURE_TENANT_ID'),
],

Register the Event Listener

Laravel 11+ removed the EventServiceProvider from the app skeleton; register the Socialite provider via the Event facade in AppServiceProvider::boot.

// app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Event;
use SocialiteProviders\Manager\SocialiteWasCalled;
use SocialiteProviders\Azure\Provider as AzureProvider;

public function boot(): void
{
    Event::listen(function (SocialiteWasCalled $event) {
        $event->extendSocialite('azure', AzureProvider::class);
    });
}

After this, Socialite::driver(‘azure’) becomes available.

If on Laravel 10 or earlier, add the listener in EventServiceProvider.

// app/Providers/EventServiceProvider.php
protected $listen = [
    \SocialiteProviders\Manager\SocialiteWasCalled::class => [
        \SocialiteProviders\Azure\AzureExtendSocialite::class.'@handle',
    ],
];

Azure App Registration

  • Add a Redirect URI of type Web: https://your-domain.com/kangtva/auth/callback (match your real host; for local: http://localhost/kangtva/auth/callback).
  • Enable ID tokens (OAuth 2.0).
  • Recommended scopes: openid, profile, email.
  • Note your Client ID, Client Secret, and Tenant ID.

Routes 

  • Protect app routes with auth middleware.
  • Keep login public and named login.azure.
  • Callback route must match your Azure Redirect URI.
Route::middleware('auth')->group(function () {
    // your protected routes...
});

Route::get('/login', [AzureLoginController::class, 'index'])->name('login.azure')->middleware

Add azure_id to users

Migration:

php artisan make:migration add_azure_id_to_users_table --table=users
// in the migration's up()
Schema::table('users', function (Blueprint $table) {
    $table->string('azure_id')->nullable()->unique()->after('id');
});
php artisan migrate

Model App\Models\User

protected $fillable = ['name', 'email', 'password', 'azure_id'];

Controller

Create the Controller
Generate a new controller to manage the authentication logic:

php artisan make:controller Auth/AzureLoginController

Open the newly created app/Http/Controllers/Auth/AzureLoginController.php and add the following methods:

use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

public function redirectToAzure()
{
    return Socialite::driver('azure')
        ->scopes(['openid','profile','email'])
        ->redirect();
}

public function handleAzureCallback()
{
    try {
        $azure = Socialite::driver('azure')->user();
    } catch (\Throwable $e) {
        return redirect()->route('login')->with('error', 'Azure login failed.');
    }

    $email = $azure->getEmail()
        ?? ($azure->user['mail'] ?? $azure->user['userPrincipalName'] ?? null);

    $user = User::updateOrCreate(
        ['azure_id' => $azure->getId()],
        [
            'name' => $azure->getName() ?? $email ?? 'User',
            'email' => $email,
            'password' => bcrypt(str()->random(32)),
        ]
    );

    Auth::login($user);
    request()->session()->regenerate();

    return redirect()->intended('/');
}

Create the Login Page View

Finally, create a login button on your view that initiates the authentication process. In your resources/views/auth/login.blade.php file (or any other view), add a link to the Azure login route:

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <p>Please log in to continue.</p>

    <a href="{{ route('login.azure') }}">
        <button>Login with Microsoft Azure</button>
    </a>
</body>
</html>

Với các bước này đã hoàn tất, ứng dụng Laravel của bạn hiện đã được định cấu hình để xác thực người dùng thông qua Azure Active Directory. Khi người dùng nhấp vào nút “Login with Microsoft Azure“, họ sẽ được chuyển hướng đến Microsoft để đăng nhập và sau khi thành công, họ sẽ được chuyển hướng trở lại ứng dụng của bạn và tự động đăng nhập.

Laravel

Post navigation

Previous Post: [Istio] Custom Authorization with Istio
Next Post: [Azure] Boosting Azure Network Performance with Accelerated Networking on AKS

More Related Articles

[Rancher/API] Edit k8s resources using the Rancher API. Kubernetes
[Model/Laravel] hasMany Quan Hệ 1 Nhiều trong model Laravel
[laravel/Rancher] There are issues when retrieving Kubernetes data from Rancher by Laravel. Laravel
[Laravel] This form is not secure. Autofill has been turned off Laravel
[Laravel] Debug an object in Laravel Laravel
[Laravel] Handle datetime easily with Carbon in Laravel. Laravel

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Rancher/EKS] Rancher from v2.12.x can not work on eks cluster. April 15, 2026
  • [Telegram/Openclaw] Configure openclaw bot in a Telegram group. March 31, 2026
  • Tutorial: Gateway API + Traefik + oauth2-proxy (Microsoft Entra ID) March 30, 2026
  • Full + incremental backup: When restoring, do deleted files come back? March 27, 2026
  • [K8S] Create long-lived kubeconfig on k8s March 23, 2026

Archives

  • April 2026
  • March 2026
  • February 2026
  • January 2026
  • December 2025
  • November 2025
  • October 2025
  • September 2025
  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • AI
    • OpenClaw
  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Gateway API
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2026 NimTechnology.