Laravel quickstart
By the end you will have a new Laravel app where people sign in with authto.it, a protected /account page that
shows who they are, and a sign-out that ends both the Laravel session and the authto.it session. There is no OpenID Connect
package: one controller uses Laravel's HTTP client for the code flow (with PKCE, state and nonce) and
firebase/php-jwt to check the ID token. People are stored in Laravel's
users table, keyed by the token's sub, and signed in with Laravel's own Auth, so the
auth middleware works as usual. Tested with Laravel 13.42, firebase/php-jwt 7.2.1 and PHP 8.3.
1. Create the site
On the authto.it dashboard, open your organization and choose Add site:
| Name | Anything you like, for example "Laravel quickstart". People see it on the sign-in page. |
|---|---|
| Return address | http://localhost:8000/auth/callback |
| After sign-out address | http://localhost:8000/ |
| Type | Server-side (confidential). The site gets a client secret, shown once: copy it now. |
The site can be invite-only (only the people you add can sign in) or open to anyone. Copy the client ID and the client secret. An AI tool connected to authto.it's MCP server can create the site for you, but the client secret is only issued on the dashboard.
2. Set up the project
Create the app and add the JWT library. A new Laravel app uses SQLite and has already run its migrations.
composer create-project laravel/laravel authto-demo
cd authto-demo
composer require firebase/php-jwt
Add your site's settings to .env. APP_KEY (the app secret that signs the session cookie) is already set by
create-project.
.env
# .env (added at the end; the rest stays as Laravel made it)
AUTHTO_ISSUER=https://letme.authto.it
AUTHTO_CLIENT_ID=your-client-id
AUTHTO_CLIENT_SECRET=your-client-secret
Read them in config/services.php: add this entry inside the returned array.
config/services.php
'authto' => [
'issuer' => env('AUTHTO_ISSUER', 'https://letme.authto.it'),
'client_id' => env('AUTHTO_CLIENT_ID'),
'client_secret' => env('AUTHTO_CLIENT_SECRET'),
],
3. Add the code
Give the users table a column for authto.it's sub and one for the role. Email and password become optional:
a person who signs in by phone has no email, and nobody has a password. Create the migration with
php artisan make:migration add_authto_to_users_table, replace its contents with the file below, then run
php artisan migrate.
database/migrations/…_add_authto_to_users_table.php
<?php
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) {
// The ID token's sub: permanent for a person on your site.
$table->string('authto_sub')->nullable()->unique();
$table->string('role')->nullable();
// Phone sign-in has no email; authto.it has no passwords.
$table->string('email')->nullable()->change();
$table->string('password')->nullable()->change();
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropUnique(['authto_sub']);
$table->dropColumn(['authto_sub', 'role']);
});
}
};
Let the new columns be filled. The rest of the model is as Laravel made it.
app/Models/User.php
<?php
namespace App\Models;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
#[Fillable(['authto_sub', 'name', 'email', 'role'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable;
}
The controller does the whole sign-in and sign-out. It reads authto.it's endpoints from
AUTHTO_ISSUER + /.well-known/openid-configuration, exchanges the code with the client secret, and checks the
ID token's signature (against authto.it's published keys), iss, aud, exp and nonce
before signing the person in.
app/Http/Controllers/AuthtoController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
class AuthtoController extends Controller
{
// GET /login: send the browser to authto.it.
public function redirect(Request $request)
{
$verifier = Str::random(64);
$state = Str::random(40);
$nonce = Str::random(40);
$request->session()->put('authto', compact('verifier', 'state', 'nonce'));
$challenge = rtrim(strtr(base64_encode(
hash('sha256', $verifier, true)), '+/', '-_'), '=');
$query = http_build_query([
'response_type' => 'code',
'client_id' => config('services.authto.client_id'),
'redirect_uri' => route('authto.callback'),
'scope' => 'openid email profile',
'state' => $state,
'nonce' => $nonce,
'code_challenge' => $challenge,
'code_challenge_method' => 'S256',
], '', '&', PHP_QUERY_RFC3986);
return redirect()->away($this->oidc()['authorization_endpoint'].'?'.$query);
}
// GET /auth/callback: authto.it sends the browser back here.
public function callback(Request $request)
{
$saved = $request->session()->pull('authto');
$oidc = $this->oidc();
abort_unless($saved && hash_equals($saved['state'], (string) $request->query('state')), 403);
abort_if($request->has('error'), 403, (string) $request->query('error_description'));
abort_if($request->has('iss') && $request->query('iss') !== $oidc['issuer'], 403);
$clientId = config('services.authto.client_id');
$tokens = Http::asForm()
->withBasicAuth($clientId, config('services.authto.client_secret'))
->post($oidc['token_endpoint'], [
'grant_type' => 'authorization_code',
'code' => $request->query('code'),
'redirect_uri' => route('authto.callback'),
'code_verifier' => $saved['verifier'],
])->throw()->json();
// Checks the signature (key picked by kid) and exp.
$keys = JWK::parseKeySet(Http::get($oidc['jwks_uri'])->throw()->json());
$claims = JWT::decode($tokens['id_token'], $keys);
abort_unless($claims->iss === $oidc['issuer']
&& in_array($clientId, (array) $claims->aud, true)
&& hash_equals($saved['nonce'], $claims->nonce ?? ''), 403);
// email is missing for phone sign-in, name and role when not set.
$user = User::updateOrCreate(['authto_sub' => $claims->sub], [
'email' => $claims->email ?? null,
'name' => $claims->name ?? '',
'role' => $claims->role ?? null,
]);
Auth::login($user);
$request->session()->regenerate();
$request->session()->put('authto_id_token', $tokens['id_token']);
return redirect()->intended('/');
}
// POST /logout: end the Laravel session, then the authto.it one.
public function logout(Request $request)
{
$idToken = $request->session()->get('authto_id_token');
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
$query = http_build_query([
'client_id' => config('services.authto.client_id'),
'id_token_hint' => $idToken, // left out if null
// url('/') has no trailing slash; match the registered address.
'post_logout_redirect_uri' => url('/').'/',
], '', '&', PHP_QUERY_RFC3986);
return redirect()->away($this->oidc()['end_session_endpoint'].'?'.$query);
}
// authto.it's endpoints, read from discovery and cached for an hour.
private function oidc(): array
{
$issuer = config('services.authto.issuer');
return Cache::remember('authto.oidc.'.md5($issuer), 3600, fn () =>
Http::get($issuer.'/.well-known/openid-configuration')->throw()->json());
}
}
The routes. The sign-in route is named login, which is where the auth middleware sends signed-out visitors.
routes/web.php
<?php
use App\Http\Controllers\AuthtoController;
use Illuminate\Support\Facades\Route;
Route::view('/', 'home');
// Named "login": the auth middleware sends signed-out visitors here.
Route::get('/login', [AuthtoController::class, 'redirect'])->name('login');
Route::get('/auth/callback', [AuthtoController::class, 'callback'])->name('authto.callback');
Route::post('/logout', [AuthtoController::class, 'logout'])->name('logout');
Route::view('/account', 'account')->middleware('auth');
The home page. Sign-out is a form post, so it carries Laravel's CSRF token.
resources/views/home.blade.php
<!doctype html>
<title>Home</title>
@auth
<p>Signed in as {{ auth()->user()->name ?: auth()->user()->email }}</p>
<p><a href="/account">Account</a></p>
<form method="post" action="/logout">
@csrf
<button>Sign out</button>
</form>
@else
<p><a href="/login">Sign in</a></p>
@endauth
resources/views/account.blade.php
<!doctype html>
<title>Account</title>
<h1>Account</h1>
<ul>
<li>sub: {{ auth()->user()->authto_sub }}</li>
<li>email: {{ auth()->user()->email ?? '(none)' }}</li>
<li>name: {{ auth()->user()->name ?: '(none)' }}</li>
<li>role: {{ auth()->user()->role ?? '(none)' }}</li>
</ul>
<p><a href="/">Home</a></p>
4. Try it
php artisan serve
Open http://localhost:8000/. Use localhost, not 127.0.0.1: the return
address is built from the address in your browser and must match the one on the site exactly.
- Choose Sign in. You land on authto.it's sign-in page for your site.
- Enter your email address. authto.it emails you a code; enter it.
- You are back on the home page: "Signed in as" your name, or your email if no name is set.
- Open
/accountto see yoursub, email, name and role. - Choose Sign out. The app ends its session, sends you to authto.it to end that session too, and authto.it sends
you back to the home page, signed out.
/accountnow sends you to sign in again.
If the site is invite-only, add yourself under the site's people on the dashboard first.
5. Protect pages and use the role
Any route or group behind the auth middleware needs a signed-in person:
Route::middleware('auth')->group(function () {
Route::view('/account', 'account');
Route::get('/orders', [OrderController::class, 'index']);
});
The role is whatever you set for the person on the authto.it dashboard (it is missing when none is set). It is saved on the user at each sign-in, so a change takes effect the next time the person signs in. Define a gate for it:
app/Providers/AppServiceProvider.php
use App\Models\User;
use Illuminate\Support\Facades\Gate;
public function boot(): void
{
Gate::define('admin', fn (User $user) => $user->role === 'admin');
}
Then use it on routes, where people without the role get a 403, and in views:
Route::middleware(['auth', 'can:admin'])->group(function () {
Route::get('/admin', fn () => 'Admins only');
});
@can('admin')
<a href="/admin">Admin</a>
@endcan
Going live
- On the site in the dashboard, add your production return address (
https://example.com/auth/callback) and after-sign-out address (https://example.com/). - Keep
AUTHTO_CLIENT_SECRETandAPP_KEYin the server's environment, never in the repository. - Serve the app over HTTPS and set
SESSION_SECURE_COOKIE=trueandAPP_URL=https://example.com. Behind a load balancer or proxy, trust it ($middleware->trustProxies(at: '*')inbootstrap/app.php) so the return address is built withhttps. - Add
offline_accessto the scope only if the app calls APIs on the person's behalf after they leave; it returns a refresh token you then have to store safely. Plain sign-in does not need it. - Manage people and their roles on the dashboard. Removing or suspending a person signs them out of authto.it; your app's own session lasts until it expires or they sign out.