Social Authentication

Reduce friction by allowing users to bring their own identity. Prisma PHP integrates seamlessly with OAuth 2.0 providers via guzzlehttp.

OAuth 2.0

Standardized protocol support for secure token exchange.

Auto-Provisioning

Accounts are automatically created in your database upon first login.

Account Linking

Associate multiple providers with a single user identity.

1

Database Schema

OAuth requires specific fields to store provider tokens and link them to users. Add these models to your schema.prisma.

prisma/schema.prisma
model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
}

model Account {
  id                String  @id @default(cuid())
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String? @db.Text
  access_token      String? @db.Text
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String? @db.Text
  session_state     String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}
2

Credentials

Create an OAuth app in your provider's developer console (e.g., Google Cloud Console) and add the credentials to your .env file.

.env
# Google
AUTH_GOOGLE_ID="123...apps.googleusercontent.com"
AUTH_GOOGLE_SECRET="GOCSPX-..."

# GitHub
AUTH_GITHUB_ID="Ov23..."
AUTH_GITHUB_SECRET="a1b2..."
3

The Auth Handler

Create a dynamic route file. This single file handles both the login redirect and the callback processing.

src/app/api/auth/ [...ppauth] /route.php
<?php

use Lib\Auth\Auth;
use Lib\Auth\GithubProvider;
use Lib\Auth\GoogleProvider;
use Lib\Request;

$auth = Auth::getInstance();

// 1. If already logged in, go to dashboard
if ($auth->isAuthenticated()) {
    Request::redirect('/dashboard');
}

// 2. Initialize Providers
$auth->authProviders(
    new GithubProvider(
        $_ENV['AUTH_GITHUB_ID'],
        $_ENV['AUTH_GITHUB_SECRET']
    ),
    new GoogleProvider(
        $_ENV['AUTH_GOOGLE_ID'],
        $_ENV['AUTH_GOOGLE_SECRET'],
        // Callback URL must match exactly what you set in Google Console
        'http://localhost:3000/api/auth/callback/google'
    )
);

// 3. Fallback redirect
Request::redirect('/dashboard');
4

Frontend Implementation

Trigger the flow by linking to the sign-in URL. The structure is /api/auth/signin/{provider}.

GitHub Login
/api/auth/signin/github
Google Login
/api/auth/signin/google

Callback URL Configuration

Ensure you whitelist the correct redirect URIs in your provider's dashboard.

  • http://localhost:3000/api/auth/callback/google
  • http://localhost:3000/api/auth/callback/github