Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

C# library for Firebase Authentication

License

NotificationsYou must be signed in to change notification settings

step-up-labs/firebase-authentication-dotnet

Repository files navigation

buildlatest versionfeedz.io

FirebaseAuthentication.net is an unofficial C# implementation ofFirebase AuthenticationandFirebaseUI.

The libraries provide a drop-in auth solution that handles the flows for signing in users with email addresses and passwords, Identity Provider Sign In including Google, Facebook, GitHub, Twitter, Apple, Microsoft and anonymous sign-in.

The solution consists of 5 libraries - a base one and 4 platform specific ones:

Installation

Either via Visual StudioNuget package manager, or from command line:

# base packagedotnet add package FirebaseAuthentication.net# Platform specific FirebaseUI (has dependency on base package)dotnet add package FirebaseAuthentication.WPFdotnet add package FirebaseAuthentication.UWPdotnet add package FirebaseAuthentication.WinUI3dotnet add package FirebaseAuthentication.Maui

Use the--version option to specify apreview version to install.

Daily preview builds are also available onfeedz.io. Just add the following Package Source to your Visual Studio:

https://f.feedz.io/step-up-labs/firebase/nuget/index.json

Usage

In general the terminology and API naming conventions try to follow the official JavaScript implementation, adjusting it to fit the .NET conventions.E.g.signInWithCredential is calledSignInWithCredentialAsync because it is meant to beawaited, but otherwise the terminology should be mostly the same.

Samples

There are currently 3 sample projects in thesamples folder:

  • .NET Core Console application (uses only the base library, no UI)
  • WPF sample with UI
  • UWP sample with UI
  • WinUI3 sample with UI

Feel free to clone the repo and check them out, just don't forget to add your custom API keys and other setup (typically inProgram.cs orApp.xaml.cs).

Setup

For general Firebase setup, refer to theofficial documentation which discusses the general concepts and individual providers in detail.You might also want to check out the first two steps in thisweb documentation.Notice that Firebase doesn't officially support Windows as a platform so you will have to register your application as a web app inFirebase Console.

FirebaseAuthentication.net

The base library gives you the same features as the officialFirebase SDK Authentication, that is without any UI. Your entrypoint is theFirebaseAuthClient.

// main namespacesusingFirebase.Auth;usingFirebase.Auth.Providers;usingFirebase.Auth.Repository;// Configure...varconfig=newFirebaseAuthConfig{ApiKey="<API KEY>",AuthDomain="<DOMAIN>.firebaseapp.com",Providers=newFirebaseAuthProvider[]{// Add and configure individual providersnewGoogleProvider().AddScopes("email"),newEmailProvider()// ...},// WPF:UserRepository=newFileUserRepository("FirebaseSample")// persist data into %AppData%\FirebaseSample// UWP:UserRepository=newStorageRepository()// persist data into ApplicationDataContainer};// ...and create your FirebaseAuthClientvarclient=newFirebaseAuthClient(config);

Notice theUserRepository. This tellsFirebaseAuthClient where to store the user's credentials.By default the libraries use in-memory repository; to preserve user's credentials between application runs, useFileUserRepository (or your custom implementation ofIUserRepository).

After you have yourclient, you can sign-in or sign-up the user with any of the configured providers.

// anonymous sign invaruser=awaitclient.SignInAnonymouslyAsync();// sign up or sign in with email and passwordvaruserCredential=awaitclient.CreateUserWithEmailAndPasswordAsync("email","pwd","Display Name");varuserCredential=awaitclient.SignInWithEmailAndPasswordAsync("email","pwd");// sign in via provider specific AuthCredentialvarcredential=TwitterProvider.GetCredential("access_token","oauth_token_secret");varuserCredential=awaitclient.SignInWithCredentialAsync(credential);// sign in via web browser redirect - navigate to given uri, monitor a redirect to// your authdomain.firebaseapp.com/__/auth/handler// and return the whole redirect uri back to the client;// this method is actually used by FirebaseUIvaruserCredential=awaitclient.SignInWithRedirectAsync(provider,async uri=>{returnawaitOpenBrowserAndWaitForRedirectToAuthDomain(uri);});

As you can see the sign-in methods give you aUserCredential object, which contains anAuthCredential and aUser objects.User holds details about a user as well as some useful methods, e.g.GetIdTokenAsync() to get a validIdToken you can use as an access token to other Firebase API (e.g. Realtime Database).

// user and auth propertiesvaruser=userCredential.User;varuid=user.Uid;varname=user.Info.DisplayName;// more properties are available in user.InfovarrefreshToken=user.Credential.RefreshToken;// more properties are available in user.Credential// user methodsvartoken=awaituser.GetIdTokenAsync();awaituser.DeleteAsync();awaituser.ChangePasswordAsync("new_password");awaituser.LinkWithCredentialAsync(authCredential);

To sign out a user simply call

client.SignOut();

FirebaseUI

The platform specific UI libraries use theFirebaseAuthClient under the hood, but need to be initilized via the staticInitialize method ofFirebaseUI:

// Initialize FirebaseUI during your application startup (e.g. App.xaml.cs)FirebaseUI.Initialize(newFirebaseUIConfig{ApiKey="<API KEY>",AuthDomain="<DOMAIN>.firebaseapp.com",Providers=newFirebaseAuthProvider[]{newGoogleProvider().AddScopes("email"),newEmailProvider()// and others},PrivacyPolicyUrl="<PP URL>",TermsOfServiceUrl="<TOS URL>",IsAnonymousAllowed=true,UserRepository=newFileUserRepository("FirebaseSample")// persist data into %AppData%\FirebaseSample});

Notice theUserRepository. This tells FirebaseUI where to store the user's credentials.By default the libraries use in-memory repository; to preserve user's credentials between application runs, useFileUserRepository (or your custom implementation ofIUserRepository).

FirebaseUI comes withFirebaseUIControl you can use in your xaml as follows:

<!--WPF Sample--><Pagex:Class="Firebase.Auth.Wpf.Sample.LoginPage"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:firebase="clr-namespace:Firebase.Auth.UI;assembly=Firebase.Auth.UI.WPF"mc:Ignorable="d"d:DesignHeight="450"d:DesignWidth="800">    <Grid>        <firebase:FirebaseUIControl>            <firebase:FirebaseUIControl.Header><!--Custom content shown above the provider buttons-->                <ImageHeight="150"Source="/Assets/firebase.png"                    />            </firebase:FirebaseUIControl.Header>        </firebase:FirebaseUIControl>    </Grid></Page>

Toggling the visibility of this UI control is up to you, depending on your business logic.E.g. you could show it as a popup, or aPage inside aFrame etc.You would typically want to toggle the control's visibility in response to theAuthStateChanged event:

// subscribe to auth state changesFirebaseUI.Instance.Client.AuthStateChanged+=this.AuthStateChanged;privatevoidAuthStateChanged(objectsender,UserEventArgse){// the callback is not guaranteed to be on UI threadApplication.Current.Dispatcher.Invoke(()=>{if(e.User==null){// no user is signed in (first run of the app, user signed out..), show login UIthis.ShowLoginUI();}elseif(this.loginUIShowing){// user signed in (or was already signed in), hide the login UI// this event can be raised multiple times (e.g. when access token gets refreshed), you need to be ready for thatthis.HideLoginUI();}});}

Packages

No packages published

Contributors15


[8]ページ先頭

©2009-2025 Movatter.jp