benxu.AppPlatform.Firebase.Auth 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package benxu.AppPlatform.Firebase.Auth --version 1.0.0
                    
NuGet\Install-Package benxu.AppPlatform.Firebase.Auth -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="benxu.AppPlatform.Firebase.Auth" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="benxu.AppPlatform.Firebase.Auth" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="benxu.AppPlatform.Firebase.Auth" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add benxu.AppPlatform.Firebase.Auth --version 1.0.0
                    
#r "nuget: benxu.AppPlatform.Firebase.Auth, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package benxu.AppPlatform.Firebase.Auth@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=benxu.AppPlatform.Firebase.Auth&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=benxu.AppPlatform.Firebase.Auth&version=1.0.0
                    
Install as a Cake Tool

benxu.AppPlatform.Firebase.Auth

Firebase Authentication 實作套件 - 提供 Google Sign-In、Email/Password 認證與自動 Token 刷新功能。

特色

  • Google 登入支援
  • Email/Password 登入與註冊
  • 自動 Token 刷新(在過期前自動更新)
  • 事件驅動架構(AuthStateChanged 事件)
  • 與 AppStateManager 自動同步
  • 模擬模式支援(無需真實 Firebase 設定)

安裝

dotnet add package benxu.AppPlatform.Firebase.Auth

使用方式

1. 註冊服務

MauiProgram.cs 中(透過 Bootstrap):

using benxu.AppPlatform.MAUI.Bootstrap.Extensions;

builder.UseAppPlatform(options =>
{
    // 使用預設設定
    options.UseFirebaseAuth();

    // 或自訂設定
    options.UseFirebaseAuth(auth =>
    {
        auth.EnableAutoTokenRefresh = true;
        auth.TokenRefreshBufferMinutes = 5;
        auth.SimulatorMode = true; // 使用模擬模式
    });
});

2. 在頁面中使用

@inject IAuthService AuthService

@code {
    private async Task SignInWithGoogle()
    {
        var result = await AuthService.SignInWithGoogleAsync();

        if (result.IsSuccess)
        {
            var user = result.Data.User;
            Console.WriteLine($"登入成功: {user.Email}");
        }
        else
        {
            Console.WriteLine($"登入失敗: {result.ErrorMessage}");
        }
    }

    private async Task SignInWithEmail()
    {
        var result = await AuthService.SignInWithEmailAsync("user@example.com", "password123");

        if (result.IsSuccess)
        {
            Console.WriteLine("Email 登入成功");
        }
    }

    private async Task SignUp()
    {
        var result = await AuthService.SignUpWithEmailAsync("newuser@example.com", "password123");

        if (result.IsSuccess)
        {
            Console.WriteLine("註冊成功");
        }
    }

    private async Task SignOut()
    {
        var result = await AuthService.SignOutAsync();

        if (result.IsSuccess)
        {
            Console.WriteLine("登出成功");
        }
    }
}

3. 訂閱認證狀態變更

@implements IDisposable

protected override void OnInitialized()
{
    AuthService.AuthStateChanged += OnAuthStateChanged;
}

private void OnAuthStateChanged(object? sender, AuthStateChangedEventArgs e)
{
    if (e.NewState.IsAuthenticated)
    {
        Console.WriteLine($"使用者已登入: {e.NewState.User?.Email}");
    }
    else
    {
        Console.WriteLine("使用者已登出");
    }

    InvokeAsync(StateHasChanged);
}

public void Dispose()
{
    AuthService.AuthStateChanged -= OnAuthStateChanged;
}

4. 取得當前使用者

var user = await AuthService.GetCurrentUserAsync();
if (user != null)
{
    Console.WriteLine($"當前使用者: {user.Email}");
}

5. 檢查 Token 是否有效

var isValid = await AuthService.IsTokenValidAsync();
if (!isValid)
{
    // Token 已過期,需要重新登入或刷新
    var result = await AuthService.RefreshTokenAsync();
}

自動 Token 刷新

啟用 EnableAutoTokenRefresh 後,服務會自動處理 Token 刷新:

options.UseFirebaseAuth(auth =>
{
    auth.EnableAutoTokenRefresh = true;
    auth.TokenRefreshBufferMinutes = 5; // 在過期前 5 分鐘刷新
});

刷新機制:

  • 登入成功後自動啟動刷新排程
  • 在 Token 過期前 N 分鐘自動刷新
  • 刷新成功後重新排程下次刷新
  • 刷新失敗會停止自動刷新
  • 登出時停止刷新排程

模擬模式 vs 真實模式

模擬模式(預設)

options.UseFirebaseAuth(auth =>
{
    auth.SimulatorMode = true; // 預設值
});

特性:

  • 不需要真實的 Firebase 專案設定
  • 接受任何 Email/Password(密碼長度 >= 6)
  • 自動產生模擬 Token
  • 完整的功能展示
  • 適合開發與測試

真實模式(未來支援)

options.UseFirebaseAuth(auth =>
{
    auth.SimulatorMode = false;
});

需求:

  • Firebase 專案設定檔(google-services.json / GoogleService-Info.plist)
  • Firebase Authentication 啟用
  • Google Sign-In 設定(如使用 Google 登入)
  • 真實的 Firebase SDK NuGet 套件

錯誤處理

所有方法都回傳 Result<T>Result

var result = await AuthService.SignInWithEmailAsync(email, password);

if (result.IsSuccess)
{
    // 成功
    var loginResponse = result.Data;
}
else
{
    // 失敗
    Console.WriteLine($"錯誤: {result.ErrorMessage}");
    Console.WriteLine($"錯誤代碼: {result.ErrorCode}");

    if (result.Exception != null)
    {
        Console.WriteLine($"例外: {result.Exception.Message}");
    }
}

常見錯誤代碼:

  • AUTH_INVALID_INPUT - 輸入驗證失敗
  • AUTH_WEAK_PASSWORD - 密碼強度不足
  • AUTH_NOT_AUTHENTICATED - 未登入
  • AUTH_TOKEN_EXPIRED - Token 已過期
  • AUTH_REFRESH_FAILED - Token 刷新失敗

與 AppStateManager 整合

FirebaseAuthService 會自動同步狀態到 IAppStateManager

@inject IAppStateManager StateManager

// 認證狀態會自動更新到 StateManager
var currentAuth = StateManager.CurrentState.Auth;
Console.WriteLine($"是否已登入: {currentAuth.IsAuthenticated}");
Console.WriteLine($"使用者: {currentAuth.User?.Email}");
Console.WriteLine($"Token 過期時間: {currentAuth.Token?.ExpiresAt}");

依賴項目

  • benxu.AppPlatform.Core - 核心抽象層
  • Microsoft.Extensions.DependencyInjection.Abstractions
  • Microsoft.Extensions.Logging.Abstractions

授權

MIT License - Copyright (c) 2025 benxu

Product Compatible and additional computed target framework versions.
.NET net8.0-android34.0 is compatible.  net8.0-ios18.0 is compatible.  net9.0-android was computed.  net9.0-ios was computed.  net10.0-android was computed.  net10.0-ios was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on benxu.AppPlatform.Firebase.Auth:

Package Downloads
benxu.AppPlatform.MAUI.Bootstrap

Bootstrap package for benxu App Platform. Provides fluent API for one-line service registration and lifecycle management.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.0.4 98 2/14/2026
3.0.3 91 2/14/2026
3.0.2 111 1/17/2026
3.0.0 103 1/13/2026
2.0.0 102 1/11/2026
1.0.0 108 12/28/2025