laravel-saml2 icon indicating copy to clipboard operation
laravel-saml2 copied to clipboard

How to check "isAuthenticated()"

Open wisnetmark opened this issue 2 years ago • 2 comments

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?

wisnetmark avatar Nov 17 '22 16:11 wisnetmark

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.

breart avatar Nov 20 '22 12:11 breart

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());
}

} `

saeed393 avatar Nov 23 '22 07:11 saeed393