24Slides / laravel-saml2

[Laravel 5.4+] An integration to add SSO to your service via SAML2 protocol based on OneLogin toolkit with support of multiple Identity Providers
MIT License
227 stars 67 forks source link

How to check "isAuthenticated()" #47

Open wisnetmark opened 1 year ago

wisnetmark commented 1 year ago

Not so much an issue but more of a question. I'm trying to use the Auth->isAuthenticated() function but can't for the life of me get the Auth model instantiated without jumping through a bunch of hoops trying to reverse engineer the middleware that sets the settings and everything. Has anyone done this before on this?

breart commented 1 year ago

The actual user authentication is not handled by this library — that you have to do by yourself.

The middleware resolves a tenant, meaning it identifies an Identity Provider that makes a request and applies the configuration. Then you can use an event SignedIn and do your magic logging in the actual user based on the attributes you get.

saeed393 commented 1 year ago

Hi, @wisnetmark This is a sample SignedInListener code.

`<?php

namespace App\Listeners;

use App\Core\SsoUser; use App\Helpers\Logger; use App\Models\User; use Slides\Saml2\Events\SignedIn; use Illuminate\Support\Facades\Auth;

class SignedInListener {

/**
 * Handle the event.
 *
 * @param SignedIn $event
 * @return void
 */
public function handle(SignedIn $event)
{
    try {
        $samlUser = $event->user;

        if ($event->auth->isAuthenticated()) {
            Logger::sso()->info('User is authenticated with attributes: ', $samlUser->getAttributes());

        } else {
            Logger::sso()->info('User is not authenticated.');
            Logger::sso()->error('Last error : ' . $event->auth->getLastErrorReason());
        }

        $user = new SsoUser();
        $user->setSsoAttributes($samlUser->getAttributes());

        if ($bsUser = $user->getUser()) {
            Auth::login($bsUser);

            if (Auth::check()) {
                Logger::sso()->info($bsUser->email . ' signed-in successfully via sso.');

            }
        } else {
            Logger::sso()->error('User Not Found.');
        }

    } catch (\Exception $exception) {
        Logger::sso()->error(__METHOD__ . ' Exception: ' . $exception->getMessage());
    }

}

public function failed(SignedIn $event, $exception)
{
    Logger::sso()->error('SignedIn listener failed. Error: ' . $exception->getMessage());
}

} `