Back

Step by Step Guide to Building a Firebase Auth API Integration in PHP

Aug 8, 20247 minute read

Introduction

Hey there, fellow PHP enthusiasts! Ready to supercharge your app's authentication system? Look no further than Firebase Auth. It's like having a security guard for your app, but way cooler and less intimidating. In this guide, we'll walk through integrating Firebase Auth into your PHP application. Trust me, your future self will thank you for this level-up in user management.

Prerequisites

Before we dive in, let's make sure we've got our ducks in a row:

  • A PHP environment that's up and running
  • A Firebase project (if you don't have one, it's time to make friends with the Firebase Console)
  • Composer installed (because who doesn't love a good package manager?)

Got all that? Great! Let's roll up our sleeves and get to work.

Installation and Setup

First things first, let's get the Firebase PHP SDK on board:

composer require kreait/firebase-php

Now, let's set up our Firebase credentials. Create a new PHP file (let's call it firebase-config.php) and add this:

<?php require __DIR__.'/vendor/autoload.php'; use Kreait\Firebase\Factory; $factory = (new Factory) ->withServiceAccount('/path/to/your/serviceAccountKey.json') ->withDatabaseUri('https://your-project-id.firebaseio.com'); $auth = $factory->createAuth();

Replace the path and URI with your actual Firebase project details. Don't worry, it's not rocket science!

Implementing Firebase Auth Features

User Registration

Let's start by adding new users to our Firebase family:

try { $userProperties = [ 'email' => '[email protected]', 'emailVerified' => false, 'password' => 'secretPassword', 'displayName' => 'John Doe', ]; $createdUser = $auth->createUser($userProperties); echo 'Successfully created new user: '.$createdUser->uid; } catch (\Kreait\Firebase\Exception\Auth\EmailExists $e) { echo 'Email already exists'; }

User Login

Time to roll out the welcome mat:

try { $signInResult = $auth->signInWithEmailAndPassword($email, $password); $user = $signInResult->data(); echo 'Welcome back, '.$user['displayName'].'!'; } catch (\Kreait\Firebase\Exception\Auth\InvalidPassword $e) { echo 'Invalid password'; }

Password Reset

Everyone forgets sometimes. Let's make it easy for them:

try { $auth->sendPasswordResetLink($email); echo 'Password reset email sent'; } catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) { echo 'No user found with this email address'; }

User Profile Management

People change, and so should their profiles:

try { $properties = [ 'displayName' => 'Jane Doe', 'photoUrl' => 'http://example.com/jane-doe.jpg', ]; $updatedUser = $auth->updateUser($uid, $properties); echo 'Successfully updated user'; } catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) { echo 'User not found'; }

Custom Claims

Want to give some users superpowers? Custom claims to the rescue:

$auth->setCustomUserClaims($uid, ['admin' => true]); // Later, to verify: $token = $auth->verifyIdToken($idToken); $claims = $token->claims()->get('admin'); if ($claims === true) { echo 'User is an admin'; }

Securing API Endpoints

Let's lock down those endpoints:

function verifyToken($token) { global $auth; try { $verifiedIdToken = $auth->verifyIdToken($token); return $verifiedIdToken->claims()->get('sub'); } catch (\Exception $e) { return null; } } // Use it in your API $token = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; $uid = verifyToken($token); if ($uid) { // Proceed with the API call } else { http_response_code(401); echo json_encode(['error' => 'Unauthorized']); exit; }

Error Handling and Best Practices

Always expect the unexpected:

  • Wrap Firebase operations in try-catch blocks
  • Use specific exception types for precise error handling
  • Never expose sensitive information in error messages
  • Implement rate limiting to prevent abuse

Testing the Integration

Don't forget to test! Here's a quick example using PHPUnit:

public function testUserCreation() { $email = '[email protected]'; $password = 'testPassword123'; $user = $this->auth->createUser([ 'email' => $email, 'password' => $password, ]); $this->assertNotNull($user->uid); $this->assertEquals($email, $user->email); }

Conclusion

And there you have it! You've just leveled up your PHP app with Firebase Auth. Remember, this is just the beginning. Firebase offers a treasure trove of features waiting to be explored. So go forth, authenticate with confidence, and may your users always stay secure!

Happy coding, and don't forget to high-five yourself for making it this far. You've earned it! 🚀👨‍💻👩‍💻