PHP code example of uptd-pelita / sso-broker-sdk

1. Go to this page and download the library: Download uptd-pelita/sso-broker-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

uptd-pelita / sso-broker-sdk example snippets


// In routes/web.php

// Require SSO authentication
Route::middleware('sso.auth')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

// Require specific role
Route::middleware('sso.role:admin')->group(function () {
    Route::get('/admin', [AdminController::class, 'index']);
});

// Require any of multiple roles
Route::middleware('sso.role:admin,editor,manager')->group(function () {
    Route::get('/manage', [ManageController::class, 'index']);
});

use Baliprov\SSOBroker\Facades\SSOBroker;

// Check if authenticated
if (SSOBroker::isAuthenticated()) {
    // User is logged in
}

// Get user data
$user = SSOBroker::getUser();

// Get user roles
$roles = SSOBroker::getRoles();

// Check specific role
if (SSOBroker::hasRole('admin')) {
    // User has admin role
}

// Check any of multiple roles
if (SSOBroker::hasAnyRole(['admin', 'editor'])) {
    // User has at least one of these roles
}

// Get SSO user ID
$ssoUserId = SSOBroker::getSSOUserId();

// Set intended URL before redirecting to SSO
SSOBroker::setIntendedUrl('/dashboard');

use Baliprov\SSOBroker\SSOBrokerManager;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    protected SSOBrokerManager $sso;

    public function __construct(SSOBrokerManager $sso)
    {
        $this->sso = $sso;
    }

    public function login(Request $request)
    {
        return $this->sso->authenticate($request);
    }

    public function logout(Request $request)
    {
        return $this->sso->logoutAndRedirect($request);
    }
}



namespace App\Http\Controllers;

use Baliprov\SSOBroker\Http\Controllers\SSOBrokerController as BaseSSOController;
use Illuminate\Http\Request;

class SSOController extends BaseSSOController
{
    /**
     * Override callback handling
     */
    public function callback(Request $request, ?string $authData = null)
    {
        // Custom logic before callback
        $this->beforeCallback($request);

        $response = parent::callback($request, $authData);

        // Custom logic after callback
        $this->afterCallback($request);

        return $response;
    }

    protected function beforeCallback(Request $request)
    {
        // Add custom logging, etc.
    }

    protected function afterCallback(Request $request)
    {
        // Sync user to local database, etc.
    }
}



namespace App\Services;

use App\Models\User;
use Baliprov\SSOBroker\SSOBrokerManager;

class CustomSSOManager extends SSOBrokerManager
{
    /**
     * Custom authorization check
     */
    protected function checkAuthorization(object $payload): bool
    {
        // Only allow specific roles
        $allowedRoles = ['admin', 'staff', 'operator'];
        $userRoles = $payload->roles ?? [];

        return !empty(array_intersect($allowedRoles, $userRoles));
    }

    /**
     * Hook after successful authentication
     */
    protected function afterSuccessfulAuth(object $payload): void
    {
        // Sync user to local database
        User::findOrCreateFromSSO($payload);

        // Log authentication
        activity()
            ->causedBy(User::bySSOUserId($payload->user->id)->first())
            ->log('User logged in via SSO');
    }

    /**
     * Custom error handling
     */
    protected function handleAuthError(string $message)
    {
        // Log error
        \Log::error('SSO Auth Error: ' . $message);

        // Custom redirect
        return redirect()->route('login.error')->with('error', $message);
    }
}

// In AppServiceProvider.php

public function register()
{
    $this->app->singleton('sso-broker', function ($app) {
        return new \App\Services\CustomSSOManager();
    });
}



namespace App\Models;

use Baliprov\SSOBroker\Contracts\SSOUserInterface;
use Baliprov\SSOBroker\Traits\HasSSOAuthentication;
use Illuminate\Database\Eloquent\Model;

class User extends Model implements SSOUserInterface
{
    use HasSSOAuthentication;

    protected $fillable = [
        'sso_user_id',
        'name',
        'email',
        'nip',
        'unit_kerja',
    ];

    /**
     * Customize SSO ID column name
     */
    protected static function getSSOIdColumn(): string
    {
        return 'sso_user_id';
    }

    /**
     * Customize attribute mapping for new users
     */
    protected static function getSSOAttributeMapping(): array
    {
        return [
            'sso_user_id' => 'id',
            'name' => 'name',
            'email' => 'email',
            'nip' => 'nip',
            'unit_kerja' => fn($payload) => $payload->user->unit_kerja->nama ?? null,
        ];
    }

    /**
     * Customize attribute mapping for updates
     */
    protected static function getSSOUpdateMapping(): array
    {
        return [
            'name' => 'name',
            'email' => 'email',
        ];
    }
}

use App\Models\User;
use Baliprov\SSOBroker\Facades\SSOBroker;

// Get current authenticated user as model
$user = User::currentSSOUser();

// Or manually find/create from payload
$payload = SSOBroker::getUser();
$user = User::findOrCreateFromSSO($payload);

// Check SSO roles on model
if ($user->hasSSORole('admin')) {
    // ...
}

// In .env
SSO_LOAD_DEFAULT_ROUTES=false

// In routes/web.php

use App\Http\Controllers\SSOController;

Route::prefix('auth')->group(function () {
    Route::get('/login', [SSOController::class, 'authenticate'])->name('login');
    Route::get('/callback/{authData?}', [SSOController::class, 'callback'])->name('sso.callback');
    Route::post('/logout-callback', [SSOController::class, 'logout'])->name('sso.logout');
    Route::get('/logout', [SSOController::class, 'userLogout'])->name('logout');
});



namespace App\Http\Middleware;

use Baliprov\SSOBroker\Http\Middleware\SSOAuthenticated as BaseMiddleware;
use Illuminate\Http\Request;

class SSOAuth extends BaseMiddleware
{
    protected function handleUnauthenticated(Request $request)
    {
        // Store additional data before redirect
        session(['login_attempt_url' => $request->fullUrl()]);

        // Custom redirect logic
        if ($request->is('api/*')) {
            return response()->json([
                'error' => 'Unauthorized',
                'login_url' => route('sso.authenticate'),
            ], 401);
        }

        return parent::handleUnauthenticated($request);
    }
}

protected $middlewareAliases = [
    // ...
    'sso.auth' => \App\Http\Middleware\SSOAuth::class,
];

use Baliprov\SSOBroker\JWT\JWT;

// Encode data to JWT
$token = JWT::encode(['user_id' => 1, 'name' => 'John']);

// Decode JWT
$payload = JWT::decode($token);

// Or use instance methods
$jwt = new JWT();
$jwt->setPayloadJWT(['user_id' => 1]);
$token = $jwt->encodeJWT();

$jwt->setJWTString($token);
$payload = $jwt->decodeJWT();



use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('sso_user_id')->nullable()->unique()->after('id');
            $table->index('sso_user_id');
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('sso_user_id');
        });
    }
};
bash
php artisan vendor:publish --tag=sso-broker-config
bash
php artisan vendor:publish --tag=sso-broker-routes