Laravel

A complete integration for a Laravel app with web sessions: configuration, routes, the redirect to Sentra, a callback that checks state, the code exchange, linking by sentra_id, and your app’s session.

1. Configuration

Register the app in the console with the Redirect URI https://api.belajar.contoh.id/auth/sso/callback, then copy the .env from the console into your app’s .env.

SSO_BASE_URL=https://sso.sentratechnology.com
SSO_API_URL=https://api.sso.sentratechnology.com
SSO_APP_ID=app_9fk2mq7xlr4tzw8nb3vh5cyd
SSO_CLIENT_SECRET=sec_...
SSO_REDIRECT_URI=https://api.belajar.contoh.id/auth/sso/callback

Add a sentra entry to config/services.php:

'sentra' => [
    'base_url'      => env('SSO_BASE_URL'),
    'api_url'       => env('SSO_API_URL'),
    'app_id'        => env('SSO_APP_ID'),
    'client_secret' => env('SSO_CLIENT_SECRET'),
    'redirect_uri'  => env('SSO_REDIRECT_URI'),
],
Keep SESSION_SAME_SITE at lax (Laravel’s default). With strict, the browser doesn’t send the session cookie when Sentra sends the user back, so state isn’t found and the callback always fails.

2. The sentra_id column

Store sentra_id on the users table. It’s unique and nullable, so existing users stay until they’re linked. Local email and password become optional because Sentra users don’t need them.

php artisan make:migration add_sentra_id_to_users_table
public function up(): void
{
    Schema::table('users', function (Blueprint $table) {
        $table->uuid('sentra_id')->nullable()->unique()->after('id');
        $table->string('email')->nullable()->change();
        $table->string('password')->nullable()->change();
    });
}

Add sentra_id to $fillable on the User model. On Laravel 10 and earlier, change() needs the doctrine/dbal package.

3. Routes

Both routes use the web middleware (the default in routes/web.php) because state and code_verifier live in the session.

use App\Http\Controllers\Auth\SentraController;

Route::get('/auth/sso/redirect', [SentraController::class, 'redirect'])->name('sso.redirect');
Route::get('/auth/sso/callback', [SentraController::class, 'callback'])->name('sso.callback');
Route::post('/logout', [SentraController::class, 'logout'])->middleware('auth')->name('logout');

The sign-in button is just a link to the redirect route:

<a href="{{ route('sso.redirect') }}">Sign in with Sentra</a>

Also set the login URL (URL masuk aplikasi in the console) to https://api.belajar.contoh.id/auth/sso/redirect, so users can open your app from their Sentra Account. See Open apps from the Account.

4. Send the user to Sentra

Create app/Http/Controllers/Auth/SentraController.php. The redirect method generates state and a PKCE code_verifier, keeps them in the session, then sends the user to /authorize.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class SentraController extends Controller
{
    public function redirect(Request $request): RedirectResponse
    {
        $state = Str::random(40);
        $verifier = Str::random(64);
        $challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');

        $request->session()->put(['sentra_state' => $state, 'sentra_verifier' => $verifier]);

        $url = config('services.sentra.base_url').'/authorize?'.http_build_query([
            'response_type'         => 'code',
            'client_id'             => config('services.sentra.app_id'),
            'redirect_uri'          => config('services.sentra.redirect_uri'),
            'state'                 => $state,
            'code_challenge'        => $challenge,
            'code_challenge_method' => 'S256',
        ]);

        return redirect()->away($url);
    }

5. Callback: check state, exchange the code

Sentra returns to your Redirect URI with code and state, or with error and state when the user denies access. Check state first, then exchange the code from your server within 60 seconds.

    public function callback(Request $request): RedirectResponse
    {
        $state = $request->session()->pull('sentra_state');
        abort_unless($state && hash_equals($state, (string) $request->query('state')), 403);
        $verifier = $request->session()->pull('sentra_verifier');

        if ($request->filled('error')) {
            return redirect()->route('login')->withErrors(['sso' => 'Sign-in with Sentra was cancelled.']);
        }

        try {
            $response = Http::asForm()
                ->withBasicAuth(config('services.sentra.app_id'), config('services.sentra.client_secret'))
                ->post(config('services.sentra.api_url').'/oauth/token', [
                    'grant_type'    => 'authorization_code',
                    'code'          => $request->query('code'),
                    'redirect_uri'  => config('services.sentra.redirect_uri'),
                    'code_verifier' => $verifier,
                ])
                ->throw();
        } catch (RequestException $e) {
            report($e);

            return redirect()->route('login')->withErrors(['sso' => 'Sign-in with Sentra failed. Try again.']);
        }

        $user = $response->json('user');
A code works only once. If the exchange fails, don’t retry with the same code; send the user to sign in again. Every error is explained in Error codes.

Look local users up by sentra_id only. Never link automatically on email, username or credential. This example creates a new user when there’s none yet:

        $account = User::updateOrCreate(
            ['sentra_id' => $user['sentra_id']],
            ['name' => $user['name']],
        );

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

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

    public function logout(Request $request): RedirectResponse
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/');
    }
}

Only accept users already registered in your app? Replace updateOrCreate with a plain lookup:

$account = User::firstWhere('sentra_id', $user['sentra_id']);

if (! $account) {
    return redirect()->route('login')->withErrors(['sso' => 'This account isn’t registered in this app yet.']);
}

$account->update(['name' => $user['name']]);

Existing users can be linked before their first sign-in with the sentra_ids from an import result. See User import.

7. Roles

$user['roles'] holds the role keys from your app’s Peran aplikasi catalog that a Sentra admin gave this user. Treat them as information: your app decides what they mean.

if (array_intersect($user['roles'], ['editor', 'penulis']) === []) {
    return redirect()->route('login')->withErrors(['sso' => 'You don’t have access to this app yet.']);
}

8. Sign out

The logout route only ends your app’s session. The Sentra session keeps running, so clicking Sign in with Sentra again signs the user straight in without a password. Send prompt=login to /authorize if you want the user to enter their password again. All parameters are in Endpoints.