Third-Party Authentication

Third-party authentication allows users to sign in using accounts from Google, GitHub, Facebook and more. This avoids creating new credentials and provides secure login with OAuth 2.0.

Overview

Third-party authentication allows users to sign in with existing accounts on services like Google and GitHub. This improves the user experience and reduces the need for password management.

Prisma PHP integrates OAuth 2.0 providers using the guzzlehttp/guzzle package, which handles HTTP requests needed to perform the OAuth exchange for authorization codes and access tokens.

Setting Up Third-Party Authentication

To begin, create an OAuth application in the provider you plan to use (Google, GitHub, etc.). You will obtain a CLIENT ID and CLIENT SECRET, as well as configure a callback URL.

The callback URL is where the user is redirected after sign-in. It is used to exchange the authorization code for an access token.

Environment Variables


AUTH_GOOGLE_ID=your-client-id
AUTH_GOOGLE_SECRET=your-client-secret

AUTH_GITHUB_ID=your-client-id
AUTH_GITHUB_SECRET=your-client-secret

Signin Route

Create this route inside: /api/auth/[...pphpauth]/route.php


<div class="flex gap-4 items-center">
    <a href="/api/auth/signin/github">
        Github
    </a>
</div>

For testing dynamic route parameters:


<?php
echo json_encode($dynamicRouteParams);
?>

Route Handler


<?php

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

$auth = Auth::getInstance();

if ($auth->isAuthenticated()) 
    redirect('/dashboard');


$auth->authProviders(
    new GithubProvider(
        $_ENV['AUTH_GITHUB_CLIENT_ID'],
        $_ENV['AUTH_GITHUB_CLIENT_SECRET']
    ),
    new GoogleProvider(
        $_ENV['AUTH_GOOGLE_CLIENT_ID'],
        $_ENV['AUTH_GOOGLE_CLIENT_SECRET'],
        "http://localhost:3000/api/auth/callback/google"
    )
);

redirect('/dashboard');

Callback Routes

Local development:

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

Production example:

  • https://yourdomain.com/api/auth/callback/google
  • https://yourdomain.com/api/auth/callback/github

Database Schema


model User 
    id            String    @id @default(cuid())
    name          String?
    email         String   @unique
    emailVerified DateTime?
    image         String?
    createdAt     DateTime @default(now())
    updatedAt     DateTime @updatedAt

    Session Session[]
    Account Account?


model Account 
    id                String   @id @default(cuid())
    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?
    createdAt         DateTime @default(now())
    updatedAt         DateTime @updatedAt

    userId String @unique
    user   User?  @relation(fields: [userId], references: [id])

    @@unique([provider, providerAccountId])
    @@index([userId])


model Session 
    id           String   @id @default(cuid())
    sessionToken String   @unique
    expires      DateTime
    createdAt    DateTime @default(now())
    updatedAt    DateTime @updatedAt

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

    @@index([userId])


model VerificationToken 
    identifier String
    token      String
    expires    DateTime

    @@unique([identifier, token])

Saving Auth Info


private function saveAuthInfo($responseInfo, $accountData)
{
    $prisma = Prisma::getInstance();
    $foundUser = $prisma->user->findUnique([
        'where' => [
            'email' => $responseInfo->email,
        ],
    ]);

    if (!$foundUser) {
        $userData = [
            'name' => $responseInfo->name,
            'email' => $responseInfo->email,
            'image' => $responseInfo->picture,
            'emailVerified' => $responseInfo->email ? date("Y-m-d H:i:s") : null,
            'Account' => [
                'create' => $accountData,
            ]
        ];

        $createUser = $prisma->user->create([
            'data' => $userData,
        ]);

        if (!$createUser) {
            exit("Error occurred. Please try again.");
        }
    }
}

Conclusion

You have now fully configured third-party authentication in Prisma PHP. Users can sign in with Google or GitHub, and authentication data is stored securely using the Prisma ORM.