Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 130 additions & 0 deletions .agents/skills/firebase-auth-basics/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
---
name: firebase-auth-basics
description: Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules.
compatibility: This skill is best used with the Firebase CLI, but does not require it. Firebase CLI can be accessed through `npx -y firebase-tools@latest`.
metadata:
author: Google LLC
category: Identity
---

## Prerequisites

- **Firebase Project**: Created via
`npx -y firebase-tools@latest projects:create` (see `firebase-basics`).
- **Firebase CLI**: Installed and logged in (see `firebase-basics`).

## Core Concepts

Firebase Authentication provides backend services, easy-to-use SDKs, and
ready-made UI libraries to authenticate users to your app.

### Users

A user is an entity that can sign in to your app. Each user is identified by a
unique ID (`uid`) which is guaranteed to be unique across all providers. User
properties include:

- `uid`: Unique identifier.
- `email`: User's email address (if available).
- `displayName`: User's display name (if available).
- `photoURL`: URL to user's photo (if available).
- `emailVerified`: Boolean indicating if the email is verified.

### Identity Providers

Firebase Auth supports multiple ways to sign in:

- **Email/Password**: Basic email and password authentication.
- **Federated Identity Providers**: Google, Facebook, Twitter, GitHub,
Microsoft, Apple, etc.
- **Phone Number**: SMS-based authentication.
- **Anonymous**: Temporary guest accounts that can be linked to permanent
accounts later.
- **Custom Auth**: Integrate with your existing auth system.

Google Sign In is recommended as a good and secure default provider.

### Tokens

When a user signs in, they receive an ID Token (JWT). This token is used to
identify the user when making requests to Firebase services (Realtime Database,
Cloud Storage, Firestore) or your own backend.

- **ID Token**: Short-lived (1 hour), verifies identity.
- **Refresh Token**: Long-lived, used to get new ID tokens.

## Workflow

### 1. Provisioning

#### Option 1. Enabling Authentication via CLI

Only Google Sign In, anonymous auth, and email/password auth can be enabled via
CLI. For other providers, use the Firebase Console.

Configure Firebase Authentication in `firebase.json` by adding an 'auth' block:

```
{
"auth": {
"providers": {
"anonymous": true,
"emailPassword": true,
"googleSignIn": {
"oAuthBrandDisplayName": "Your Brand Name",
"supportEmail": "support@example.com",
"authorizedRedirectUris": [
"https://my-project-id.firebaseapp.com/__/auth/handler",
"http://localhost"
]
}
}
}
}
```

> [!NOTE] If the Google Sign-In popup opens and immediately closes with the
> error `[firebase_auth/unauthorized-domain]`, it means the domain is not
> authorized. For local development, add `http://localhost` to
> `authorizedRedirectUris` in `firebase.json` (or ensure `localhost` is included
> in the **Authorized Domains** list in the Firebase Console under
> Authentication > Settings > Authorized domains). **CRITICAL**: Do NOT include
> the port number in `authorizedRedirectUris` (e.g., use `http://localhost`, NOT
> `http://localhost:9090` or `http://localhost:4000`), and do NOT include the
> protocol or port number in the Console Authorized Domains list (use
> `localhost`). Including a port number in `authorizedRedirectUris` causes
> `firebase deploy --only auth` to fail with `INVALID_AUTHORIZED_DOMAIN`.
**CRITICAL**: After configuring `firebase.json`, you MUST deploy the auth
configuration to the Firebase backend for the changes to take effect. This is
essential for auth providers like Google Sign-In, email/password, etc. to
auto-generate the necessary OAuth clients for your app platforms. Run:

```bash
npx -y firebase-tools@latest deploy --only auth
```

#### Option 2. Enabling Authentication in Console

Enable other providers in the Firebase Console.

1. Go to the
https://console.firebase.google.com/project/_/authentication/providers
1. Select your project.
1. Enable the desired Sign-in providers (e.g., Email/Password, Google).

### 2. Client Setup & Usage

**Web** See [references/client_sdk_web.md](references/client_sdk_web.md).

**Flutter** See [references/flutter_setup.md](references/flutter_setup.md).
**Android (Kotlin)** See
[references/client_sdk_android.md](references/client_sdk_android.md).

**iOS (Swift)** See [references/ios_setup.md](references/ios_setup.md).

### 3. Security Rules

Secure your data using `request.auth` in Firestore/Storage rules.

See [references/security_rules.md](references/security_rules.md).
197 changes: 197 additions & 0 deletions .agents/skills/firebase-auth-basics/references/client_sdk_android.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
# Firebase Authentication - Android Setup Guide (Kotlin)

This guide describes the SDK setup and basic usage patterns for Firebase
Authentication in an Android app using Kotlin DSL (`build.gradle.kts`) and
Kotlin code.

## Prerequisites

IMPORTANT: Before specifically working with Firebase Authentication, make sure
to use the skill and reference `firebase_basics/references/android_setup` to
ensure the following is done.

- The Firebase CLI is available and authenticated.
- An Android project exists and is registered with a Firebase Project.
- The Android project has a Firebase config file (`google-services.json`) and
the Google services Gradle plugin (`google-services`).

______________________________________________________________________

## 1. Enable Authentication via CLI

Enable the Firebase Authentication service in the Firebase Project using the
Firebase CLI:

```bash
npx -y firebase-tools@latest init auth
```

______________________________________________________________________

## 2. Add dependencies to Gradle build files

> [!IMPORTANT] **[AGENT] RESOLVING THE SDK VERSION DETERMINISTICALLY** Never
> guess or hardcode a memorized out-of-date SDK or plugin version. Before adding
> dependencies, you MUST query the latest available versions directly from the
> Google Maven Repository:
>
> ```bash
> # Find the latest Firebase Android BoM version
> curl -s https://dl.google.com/dl/android/maven2/com/google/firebase/firebase-bom/maven-metadata.xml | grep -oE '<latest>[^<]+' | cut -d'>' -f2
>
> # Find the latest firebase-auth version
> curl -s https://dl.google.com/dl/android/maven2/com/google/firebase/firebase-auth/maven-metadata.xml | grep -oE '<latest>[^<]+' | cut -d'>' -f2
> ```
>
> If the dependency is already declared, fetch the exact resolved version
> currently active in the workspace's build graph:
>
> ```bash
> ./gradlew -q :app:dependencyInsight --dependency firebase-auth --configuration releaseRuntimeClasspath
> ```
In the **module (app-level)** `build.gradle.kts` (usually
`<project>/<app-module>/build.gradle.kts`), add the dependency for Firebase
Authentication:
```kotlin
dependencies {
// [AGENT] Fetch the latest resolved version using the Gradle command above
implementation(platform("com.google.firebase:firebase-bom:<latest_bom_version>"))
// Add the dependency for the Firebase Authentication library
// When using the BoM, don't specify versions in Firebase library dependencies
implementation("com.google.firebase:firebase-auth")
}
```
______________________________________________________________________
## 3. Initialize FirebaseAuth
In the Activity or Fragment, initialize the `FirebaseAuth` instance:
```kotlin
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
class MainActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
auth = Firebase.auth
setContent {
MaterialTheme {
Text("Auth initialized!")
}
}
}
}
```
### Jetpack Compose (Modern)
Initialize inside a `ComponentActivity` using `setContent`:
```kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import com.google.firebase.Firebase
import com.google.firebase.auth.auth
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val auth = Firebase.auth
setContent {
MaterialTheme {
Text("Auth initialized!")
}
}
}
}
```
______________________________________________________________________
## 4. Check current Auth state
Check if a user is already signed in when the activity starts:
```kotlin
public override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
if (currentUser != null) {
// User is signed in, navigate to main screen or update UI
} else {
// No user is signed in, prompt for login
}
}
```
______________________________________________________________________
## 5. Use sign-in providers in the app
### Email/Password
#### Sign up NEW users with Email/Password
Use `createUserWithEmailAndPassword` to register new users:
```kotlin
fun signUpUser(email: String, password: String) {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign up success, update UI with the signed-in user's information
val user = auth.currentUser
// Navigate to main screen
} else {
// If sign up fails, display a message to the user.
Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show()
}
}
}
```
#### Sign in EXISTING users with Email/Password
Use `signInWithEmailAndPassword` to sign in existing users:
```kotlin
fun signInUser(email: String, password: String) {
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
val user = auth.currentUser
// Navigate to main screen
} else {
// If sign in fails, display a message to the user.
Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show()
}
}
}
```
______________________________________________________________________
## 6. Sign out users
To sign out a user, call `signOut()` on the `FirebaseAuth` instance:
```kotlin
auth.signOut()
// Navigate to login screen
```
Loading
Loading