SAML toolkit for Laravel based on OneLogin's SAML PHP Toolkit.

Related tags

Laravel laravel-saml
Overview

Laravel SAML

SAML toolkit for Laravel based on OneLogin's SAML PHP Toolkit.

Installation

composer require overtrue/laravel-saml

Configuration

php artisan vendor:publish --tag=saml-config

This command will add the file config/saml.php. This config is handled almost directly by OneLogin so you may get further references there, but will cover here what's really necessary. There are some other config about routes you may want to check, they are pretty straightforward.

Usage

If your application is only used to log in to one specified IdP, you just need to configure idp section in config/saml.php.

idp configuration resolver

In order to support multiple IdP, you need to configure the following method to get the configuration of the IdP.

Saml::configureIdpUsing(function($idpName): array {
    return [...]; 
});

You need to return the configuration array for IdP, see the idp section in config/saml.php for the structure.

Entrypoints controller

You can create a controller to perform SAML integration:

$ php artisan make:controller SamlController

Then we prepare the following 5 necessary methods.



namespace App\Http\Controllers;

use Overtrue\LaravelSaml\Saml;

class SamlController extends Controller
{
    public function login() {}
    public function acs() {}
    public function logout() {}
    public function sls() {}
    public function metadata() {}
}

Entrypoints Routes

Then configure the routes at routes/web.php:

Method URI Name
GET {routesPrefix}/login saml.login
POST {routesPrefix}/acs saml.acs
GET {routesPrefix}/logout saml.logout
GET {routesPrefix}/sls saml.sls
GET {routesPrefix}/metadata saml.metadata

You are free to use your preferred routing prefix, for example, we use saml as the routing prefix:

use App\Http\Controllers\SamlController;

Route::get('saml/login', [SamlController::class, 'login'])->name('saml.login');
Route::get('saml/logout', [SamlController::class, 'logout'])->name('saml.logout');
Route::post('saml/acs', [SamlController::class, 'acs'])->name('saml.acs');
Route::get('saml/sls', [SamlController::class, 'sls'])->name('saml.sls');
Route::get('saml/metadata', [SamlController::class, 'metadata'])->name('saml.metadata');

Redirect to IdP login service

Initiates the SSO process, creates an AuthnRequest, returns a laravel redirect response.

    //<...>
    public function login(Request $request)
    {
        // Use the default idp in the configuration
        return Saml::redirect(); 
        
        // Or specify the idp name
        return Saml::idp($request->get('idp'))->redirect();
    }

Assertion Consumer Service (ACS)

This method is used to handle the IdP authorization callback, SamlAuth::getAuthenticatedUser will validation the request and return a Overtrue\LaravelSaml\SamlUser object.

//<...>
    public function acs(Request $request)
    {
        // Overtrue\LaravelSaml\SamlUser
        $samlUser = Saml::getAuthenticatedUser();
        // Or specify the idp name
        //$samlUser = Saml::idp($request->get('idp'))->getAuthenticatedUser(); 
        
        $samlUserId = $samlUser->getNameId();
        
        // SamlUser to app User
        // $user = User::FirstOrCreate(['email' => $samlUser->getNameId()]);
        Auth::set($user);
        
        return redirect('/home')
    }

Redirect to IdP logout service

Create a redirect response to IdP logout service.

    //<...>
    public function logout(Request $request)
    {
        // Use the default IdP in the configuration
        return Saml::redirectToLogout(); 
        
        // Or specify the IdP name
        return Saml::idp($request->get('idp'))->redirectToLogout();
    }

The IdP will return the Logout Response through the user's client to the Single Logout Service of the SP (route saml/sls).

Single Logout Service (SLS)

This code handles the Logout Request and the Logout Responses.

    //<...>
    public function sls(Request $request)
    {
        $auth = Saml::handleLogoutRequest();
        // Or specify the IdP name
        //$auth = Saml::idp($request->get('idp'))->handleLogoutRequest();
    
        Auth::logout();
        
        return redirect('/home')
    }

Metadata

This code will provide the XML metadata file of our SP, based on the info that we provided in the settings files.

    //<...>
    public function metadata(Request $request)
    {
        $auth = Saml::idp($idpName);
        
        if ($request->has('download')) {
            return $auth->getMetadataXMLAsStreamResponse();
            // or specify a filename to the xml file:
            // return $auth->getMetadataXMLAsStreamResponse('sp-metadata.xml');
        }
        
        return $auth->getMetadataXML();
    }

More

For more information on configuration and usage please see the source code or read onelogin/php-saml.

Contributing

You can contribute in one of three ways:

  1. File bug reports using the issue tracker.
  2. Answer questions or fix bugs on the issue tracker.
  3. Contribute new features or update the wiki.

The code contribution process is not very formal. You just need to make sure that you follow the PSR-0, PSR-1, and PSR-2 coding guidelines. Any new code contributions must be accompanied by unit tests where applicable.

PHP 扩展包开发

想知道如何从零开始构建 PHP 扩展包?

请关注我的实战课程,我会在此课程中分享一些扩展开发经验 —— 《PHP 扩展包实战教程 - 从入门到发布》

License

MIT

You might also like...
Gretel is a Laravel package for adding route-based breadcrumbs to your application.
Gretel is a Laravel package for adding route-based breadcrumbs to your application.

Gretel Laravel breadcrumbs right out of a fairy tale. Gretel is a Laravel package for adding route-based breadcrumbs to your application. Defining Bre

Package to easily test crudable controllers for Laravel based API

Laravel Crudable Test This package is very usefull to easily test crudable controllers. Installation You can install package via composer. Add reposit

A Laravel Code Generator based on your Models using Blade Template Engine
A Laravel Code Generator based on your Models using Blade Template Engine

Laravel Code Generator is a PHP Laravel Package that uses Blade template engine to generate code for you. The difference between other code generators

Stapler-based file upload package for the Laravel framework.

laravel-stapler Laravel-Stapler is a Stapler-based file upload package for the Laravel framework. It provides a full set of Laravel commands, a migrat

A TALL-based Laravel Livewire component to replace the (multiple) select HTML input form with beautiful cards.
A TALL-based Laravel Livewire component to replace the (multiple) select HTML input form with beautiful cards.

TALL multiselect cards A TALL-based Laravel Livewire component to replace the (multiple) select HTML input form with beautiful cards. Table of content

A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

A Formatter Class for Laravel 4 based on FuelPHP's Formatter Class

Changelog Update support for Laravel 6 & phpunit 8 Update composer.json Upgrade to PSR-4 add parameter newline, delimiter, enclosure, and escape to ex

 Load Laravel service providers based on your application's environment.
Load Laravel service providers based on your application's environment.

Laravel EnvProviders A more finetuned way of managing your service providers in Laravel. This package allows you to configure the environment certain

Comments
  • Usage of Saml::configureIdpUsing()

    Usage of Saml::configureIdpUsing()

    Hi overtrue !

    Hope you're well. I implement your SAML package and I got some trouble with multiple idp. Do you have any example of usage of this function (Saml::configureIdpUsing()) ? Where should I put it exactly in my code?

    Thank you,

    opened by Vicftz 5
  • Metadata with multiple IDPs

    Metadata with multiple IDPs

    Hi,

    I got a little trouble in my SAML SSO development. Is it possible to generate metadata without any default IDP ? I implemented multiple IdP (Each client will have his own idp, stored in my database). As the he metadata are not linked to the IDP, I want to give the same link to all my customers (ex : laravel.test/saml/metadata). But I need an IDP to build this object : $auth = Saml::idp();` (I commented the idp part in my config). Do you have an idea ?

    Thank you.

    opened by razvan-deskare 3
  • Avoid using `url()` in saml.php, even if it is `env()`

    Avoid using `url()` in saml.php, even if it is `env()`

    To reproduce:

    • Install Laravel 9 by running: composer create-project laravel/laravel .
    • Publish config by running: php artisan vendor:publish --tag=saml-config
    • Start server by running php artisan serve, error below:
    In UrlGenerator.php line 121:
    
      Illuminate\Routing\UrlGenerator::__construct(): Argument #2 ($request) must be of type Illuminate\Http\Request, null given, called in C:\projects\sso\vendor\laravel\framework\s   
      rc\Illuminate\Routing\RoutingServiceProvider.php on line 65
    

    After reading this: https://stackoverflow.com/questions/72520085/illuminate-routing-urlgenerator-construct-argument-2-request-must-be-o, the root cause is that in your saml.php there are several config that is using this helper function: url().

    It will still fail even if you are coding this: env('MY_ENV_VAR', url('/')) when this variable is set in .env. url() will still run in config file saml.php.

    After removing all url(), I can start my server.

    Please take a look and modify your saml.php config accordingly.

    Thank you.

    opened by alucard001 1
Releases(1.0.1)
Owner
安正超
Keep calm and coding.
安正超
laravel - Potion is a pure PHP asset manager for Laravel 5 based off of Assetic.

laravel-potion Potion is a pure PHP asset manager for Laravel based off of Assetic. Description Laravel 5 comes with a great asset manager called Elix

Matthew R. Miller 61 Mar 1, 2022
PHP package to help the development of Laravel-based Telegram bots

Laravel-telegram-bot Project description goes here. This description is usually two to three lines long. It should give an overview of what the projec

CC - UFFS 6 May 10, 2021
Laravel blade directives and php helpers for serverside rendered content, based on browser window size WITHOUT css

Laravel Window Size and Breakpoints Laravel blade directives and php helpers for server side rendered content, based on browser window size WITHOUT cs

Tina Hammar 7 Nov 23, 2022
Laravel blade directives and php helpers for serverside rendered content, based on browser window size WITHOUT css. Requires Livewire and AlpineJS.

Laravel Livewire Window Size and Breakpoints Laravel blade directives and php helpers for server side rendered content, based on browser window size W

Tina Hammar 15 Oct 6, 2022
Self-hosted CMS platform based on the Laravel PHP Framework.

October is a Content Management System (CMS) and web platform whose sole purpose is to make your development workflow simple again. It was born out of

October CMS 10.8k Jan 1, 2023
Adds phone number functionality to Laravel based on the PHP port of Google's libphonenumber API by giggsey.

Laravel Phone Adds phone number functionality to Laravel based on the PHP port of Google's libphonenumber API by giggsey. Table of Contents Demo Insta

null 2.1k Jan 2, 2023
List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova and Laravel Spark.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

Laravel Lang 6.9k Jan 2, 2023
Awes.io // boilerplate based on Vue, Nuxt, TailwindCSS plus Laravel as a backend. 🤟

Platform for Interactive Business Applications 10x faster to create than the traditional way • 3x increase application experiences • 60% decrease in d

Awes.io 753 Dec 30, 2022
MediaDB is a web-based media streaming service written in Laravel and Vue.

MediaDB (API) MediaDB is a web-based media streaming service written in Laravel and Vue. The nginx-vod-module is used for on-the-fly repackaging of MP

François M. 53 Sep 3, 2022
A simple laravel package to handle multiple key based model route binding

Laravel Model UUID A simple package to handle the multiple key/column based route model binding for laravel package Installation Require the package u

null 13 Mar 2, 2022