Coder Social home page Coder Social logo

step-up-labs / firebase-authentication-dotnet Goto Github PK

View Code? Open in Web Editor NEW
367.0 21.0 126.0 693 KB

C# library for Firebase Authentication

License: MIT License

C# 94.24% PowerShell 5.76%
firebase-authentication firebase firebase-database firebase-realtime-database

firebase-authentication-dotnet's Introduction

FirebaseAuthentication.net

build latest version feedz.io

FirebaseAuthentication.net is an unofficial C# implementation of Firebase Authentication and FirebaseUI.

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 Studio Nuget package manager, or from command line:

# base package
dotnet add package FirebaseAuthentication.net

# Platform specific FirebaseUI (has dependency on base package)
dotnet add package FirebaseAuthentication.WPF
dotnet add package FirebaseAuthentication.UWP
dotnet add package FirebaseAuthentication.WinUI3
dotnet add package FirebaseAuthentication.Maui

Use the --version option to specify a preview version to install.

Daily preview builds are also available on feedz.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 called SignInWithCredentialAsync because it is meant to be awaited, but otherwise the terminology should be mostly the same.

Samples

There are currently 3 sample projects in the samples 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 in Program.cs or App.xaml.cs).

Setup

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

FirebaseAuthentication.net

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

// main namespaces
using Firebase.Auth;
using Firebase.Auth.Providers;
using Firebase.Auth.Repository;

// Configure...
var config = new FirebaseAuthConfig
{
    ApiKey = "<API KEY>",
    AuthDomain = "<DOMAIN>.firebaseapp.com",
    Providers = new FirebaseAuthProvider[]
    {
        // Add and configure individual providers
        new GoogleProvider().AddScopes("email"),
        new EmailProvider()
        // ...
    },
    // WPF:
    UserRepository = new FileUserRepository("FirebaseSample") // persist data into %AppData%\FirebaseSample
    // UWP:
    UserRepository = new StorageRepository() // persist data into ApplicationDataContainer
};

// ...and create your FirebaseAuthClient
var client = new FirebaseAuthClient(config);

Notice the UserRepository. This tells FirebaseAuthClient where to store the user's credentials. By default the libraries use in-memory repository; to preserve user's credentials between application runs, use FileUserRepository (or your custom implementation of IUserRepository).

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

// anonymous sign in
var user = await client.SignInAnonymouslyAsync();

// sign up or sign in with email and password
var userCredential = await client.CreateUserWithEmailAndPasswordAsync("email", "pwd", "Display Name");
var userCredential = await client.SignInWithEmailAndPasswordAsync("email", "pwd");

// sign in via provider specific AuthCredential
var credential = TwitterProvider.GetCredential("access_token", "oauth_token_secret");
var userCredential = await client.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 FirebaseUI
var userCredential = await client.SignInWithRedirectAsync(provider, async uri =>
{    
    return await OpenBrowserAndWaitForRedirectToAuthDomain(uri);
});

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

// user and auth properties
var user = userCredential.User;
var uid = user.Uid;
var name = user.Info.DisplayName; // more properties are available in user.Info
var refreshToken = user.Credential.RefreshToken; // more properties are available in user.Credential

// user methods
var token = await user.GetIdTokenAsync();
await user.DeleteAsync();
await user.ChangePasswordAsync("new_password");
await user.LinkWithCredentialAsync(authCredential);

To sign out a user simply call

client.SignOut();

FirebaseUI

The platform specific UI libraries use the FirebaseAuthClient under the hood, but need to be initilized via the static Initialize method of FirebaseUI:

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

Notice the UserRepository. 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, use FileUserRepository (or your custom implementation of IUserRepository).

FirebaseUI comes with FirebaseUIControl you can use in your xaml as follows:

<!--WPF Sample-->
<Page x: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-->
                <Image 
                    Height="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 a Page inside a Frame etc. You would typically want to toggle the control's visibility in response to the AuthStateChanged event:

// subscribe to auth state changes
FirebaseUI.Instance.Client.AuthStateChanged += this.AuthStateChanged;

private void AuthStateChanged(object sender, UserEventArgs e)
{
    // the callback is not guaranteed to be on UI thread
    Application.Current.Dispatcher.Invoke(() =>
    {
        if (e.User == null)
        {
            // no user is signed in (first run of the app, user signed out..), show login UI 
            this.ShowLoginUI();
        }
        else if (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 that
            this.HideLoginUI();
        }
    });
}

firebase-authentication-dotnet's People

Contributors

anovik avatar badochov avatar bernhardgessler avatar bezysoftware avatar blemasle avatar cabauman avatar firedragonweb avatar hardcodet avatar heavymachinegun avatar itswisdomagain avatar kapusch avatar luccasclezar avatar luizfelipefm avatar mohed avatar sergeylopatyuk avatar sheindel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-authentication-dotnet's Issues

How do I know if the authentication was successful?

Hey, I've used your library and it's great. I can create users successfully, but are there any way of know if the authentication or creation of user was successful? Here's my code, but it just doesn't work

var authProvider = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyAzv7fPeoZ8_N1Ld4oFRNm-iPlz43yVpZk"));
var auth = authProvider.SignInWithEmailAndPasswordAsync(email: email, password: password);

        while (true)
        {

            if (auth.Status == TaskStatus.RanToCompletion)
            {

                Console.WriteLine("Authentication Completed successfully");

            }
            else
            {

                Console.WriteLine("Something went wrong when authenticating user!");

            }

            Thread.Sleep(500);

        }

secure a asp.net web api with firebase-authentication-dotnet

Great lib thx for your effort in this!
I am currently using Azure b2c for login and i also have a secured asp.net backend. I want to switch to firebase auth in my angular frontend which will be no problem.
Unfortunately I am stuck while trying to validate the firebase jwt token from the client in my asp backend. Is this doable with this libraray?

Problem with auth Password and Email

Hi thanks for the huge efford on this project, sorry for this but i have problems with loging in firebase with password and email, when i debbug my project, it freezed when go to authProvider.SignInWithEmailAndPasswordAsync(mail, pass).Result;. please help me i didnt know if i am doing something wrong. this is my code

private async Task Authoritation()
{
var authConfig = new FirebaseConfig(ConfigurationManager.AppSettings["ApiKeyFirebase"]);
_authProvider = new FirebaseAuthProvider(authConfig);
var mail = ConfigurationManager.AppSettings["MailFirebase"];
var pass = ConfigurationManager.AppSettings["PassFirebase"];

        return await _authProvider.SignInWithEmailAndPasswordAsync(mail, pass);
    }
    private bool Run(DatosEnvio1800 datos)
    {
        if (datos == null) return false;

        var auth = Authoritation().Result;
        var resultado = GetResultFirebase(auth, datos).Result;
        return !string.IsNullOrEmpty(resultado.Key);
    }

please help me, thanks for everything

deleteUser

Is deleteUser planned? Does it exist and I just missed it?

SignInWithEmailAndPasswordAsync broken

Here is my code:

var authProvider = new FirebaseAuthProvider(new FirebaseConfig(Properties.Resources.API_KEY));
var auth = await authProvider.SignInWithEmailAndPasswordAsync(emailText.Text, passwordText.Text);

if the credentials are correct, authentication works as expected. When the credentials are incorrect, the async method does not return thus leaving the program completely hung up.

Keep me logged in functionality

I'm creating an app in Xamarin with this library. I want a user to stay logged in, even after the app is closed.
Is FirebaseAuthentication.net capable of this? If yes, what should I save to re-authenticate at next start?
I know, I could just save email and password, but I also provide the ability to login with OAtuh token from Facebook and Google.
(I would of course use Xamarin.Auth, to securely save credential information.)

SignOut on a Windows Application

Currently I'm Signing In on Firebase like this:

Auth = new FirebaseAuthProvider(new FirebaseConfig(apiKey));
AuthLink = await Auth.SignInWithEmailAndPasswordAsync(email, password);

But now I need to SignOut in order to Sign In with other user, what's the best way or only way to do this?

Get Phonenumber from UserID

I have done a phone number authentication in Android project. In firebase, it created a UserId for that authenticated phone number. Now, I wanted to retrieve the phone number based on user id using asp.net web app.

Is there any way to get the authenticated phone number from that relevant user id? I mean is there any method or property available in this DLL to retrieve authenticated phone number using user id?

Note : I am using firebase-database-dotnet for firebase database CRUD operation.

Creating user with email/password

Hi,
Sorry to be a pest...
Any chance of a guide on how to create a user with a email/password?

Currently I have the following:

_firebaseAuth = new FirebaseAuthProvider(new FirebaseConfig("<Web API Key>"));
var resp = _firebaseAuth.CreateUserWithEmailAndPasswordAsync(email, password);
			resp.Wait();//we need the response

Looking in the debugger, it hangs on the Wait() as long as I have had the patience to wait.

Any ideas on where I should go next / How to debug?
Is there somewhere I need to give the firebase URL to auth against?
Thank you :)
(The rest of the library appears to work perfectly)!

How do you use RefreshAuthAsync?

when I see your implementation for RefreshAuthAsync, you are passing FirebaseAuth object, does it mean that we should store this object in the app because once it is expired, it will not be returned I believe, in your sample project, it seems like that you pass it null. How is the good usage of this? because I only saved refreshtoken and firebasetoken in my app.


  public async Task<FirebaseAuthLink> RefreshAuthAsync(FirebaseAuth auth)
        {
            var content = $"{{\"grant_type\":\"refresh_token\", \"refresh_token\":\"{auth.RefreshToken}\"}}";
            var responseData = "N/A";

            try
            {
                var response = await this.client.PostAsync(new Uri(string.Format(GoogleRefreshAuth, this.authConfig.ApiKey)), new StringContent(content, Encoding.UTF8, "application/json"));

                responseData = await response.Content.ReadAsStringAsync();
                var refreshAuth = JsonConvert.DeserializeObject<RefreshAuth>(responseData);

                return new FirebaseAuthLink
                {
                    AuthProvider = this,
                    User = auth.User,
                    ExpiresIn = refreshAuth.ExpiresIn,
                    RefreshToken = refreshAuth.RefreshToken,
                    FirebaseToken = refreshAuth.AccessToken
                };
            }
            catch (Exception ex)
            {
                throw new FirebaseAuthException(GoogleRefreshAuth, content, responseData, ex);
            }
        }

I can't install this from nuget package.

Could not install package 'FirebaseAuthentication.net 2.2.0'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.5,Profile=Profile259', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

Invalid auth token

After I have logged in with google account, I can no longer get valid auth token from facebook account

var firebaseAuth = await Runtime.authProveider.SignInWithOAuthAsync(provider.AuthType, access_token);

It will return the correct uid and invalid token.

xkWJee5U9yfGWWY1ETKcslffoQN2
AMzJoSli39qxf8-kVVZo6V9tmLZYsZgr0ad5nWogP-cRUf9Ab525-u0nx_grt4WaxaFJGoCZTMRZbyG_nBFysnOvzVxtdztQw1-ZqqX-RzUz_rthUgYJZpzTQGWeU5IRQlaw8VmvDFH8E7X_FCK-paJS9Tin8ikDY1AZj2MOQNop9pOqGikb2AqQYOSKEjr0QuLPgIIWqQDkyBVBt3-SxU6VYqKuAEmID5MEMPERZ4zUdjpgHAE64JPHGNGQQnfcD762M4pjPoNMqvC28KpKM1dyRESkhYhoW4iNKWPmzypzepP8CvCKQZ5bArFuyUfgbYpnNrYFC4imrcD4K12U5vezkxU2Lq1AfiHkCI4yTuq3DWhaLv6b3bFB39pjNK-6az2ERIEJbUOa0CRor7sNcRwSJwAmwN2Zor7I6KFgCpfTEJIdzXBodcRF7REW6ijDlv0KWlBtI1V1T7Eq0ZcAOse4-BSjUkzSaZ3jF6_J-qAo2NTH4ws-vJdTwYdLjCF3My8jceY3ymKuMD5o73Rg2RxMAMoAPrrkfQzXB8BO2_nVexQS9l4lFfYmz3xx7S_YwVXRXI12sQtlcOPGpO46MxjRRw_4tXICew3oAyE9TG9uVpQhZSJoSbWa_DiheRnXBet3HHYuSkJ_vEHnVvAEMe55jjfXtHmC2ke9O1QIdge8jLoDcMSh3J742FMVnU7TPnB4RD3AYMt2c5gGez_fGA3pB29wcXCpVm-sJnczgjq5XREGsbkbCsqY8IIDO3VxFC9-llXyqnE-MqYtilfg9HquWEASKB33T0WewwqPSSZA_MVWd74-_NsFAHJPTzsaFYi18Wdo5cid7Hyd5VPBvE0omJEWwORcuZvx_w2yRAonI4qjvEoKj_kCNW-SSpEbv9h5VGSx2hKoj_CRg-s2c3VsYpet23crqAZUl5z9qrfYCe7XTbDJR5wRripzd_mM-gxPdTB2x58DVcXB8dYMHyAko6qgJZwTGYjJM-hU0DVwZyl-V8mVMKl1OtLR-Txa0wfLZxRHouA6-k20hx3wdENhAlZWdX0VPND5KRtkD1Sv8kVGdg0REy6RL9_0id8v4oT_rJqXPJn7uNd3Sd1M_L6oU3Bc0XXB6muA_qHmMm9cusP5LqDyq6R0H5UNYpLtyVjjNZnJGwnlUL4KiS4qLJhcVPW-AaYn2z6VfE2fqtttjgLpci0qZaXFMWYdLR9hyK--oZmfnXUTCavpN7PrJ_jbrm0NfsNFttNPzJCwAUSfmYIOoP3nsApQYxNqiPjhMQ6Sku3Ach7S86f828vYXI8n0rPB084qNl-2Z6ZrbvTeqskyLozDWHl7kSVr6vkCucmRwBb_gUnpyK9vUR6IlRkEAy2py8kDnQ
https://test.firebaseio.com/profiles/xkWJee5U9yfGWWY1ETKcslffoQN2/.json?auth=AMzJoSli39qxf8-kVVZo6V9tmLZYsZgr0ad5nWogP-cRUf9Ab525-u0nx_grt4WaxaFJGoCZTMRZbyG_nBFysnOvzVxtdztQw1-ZqqX-RzUz_rthUgYJZpzTQGWeU5IRQlaw8VmvDFH8E7X_FCK-paJS9Tin8ikDY1AZj2MOQNop9pOqGikb2AqQYOSKEjr0QuLPgIIWqQDkyBVBt3-SxU6VYqKuAEmID5MEMPERZ4zUdjpgHAE64JPHGNGQQnfcD762M4pjPoNMqvC28KpKM1dyRESkhYhoW4iNKWPmzypzepP8CvCKQZ5bArFuyUfgbYpnNrYFC4imrcD4K12U5vezkxU2Lq1AfiHkCI4yTuq3DWhaLv6b3bFB39pjNK-6az2ERIEJbUOa0CRor7sNcRwSJwAmwN2Zor7I6KFgCpfTEJIdzXBodcRF7REW6ijDlv0KWlBtI1V1T7Eq0ZcAOse4-BSjUkzSaZ3jF6_J-qAo2NTH4ws-vJdTwYdLjCF3My8jceY3ymKuMD5o73Rg2RxMAMoAPrrkfQzXB8BO2_nVexQS9l4lFfYmz3xx7S_YwVXRXI12sQtlcOPGpO46MxjRRw_4tXICew3oAyE9TG9uVpQhZSJoSbWa_DiheRnXBet3HHYuSkJ_vEHnVvAEMe55jjfXtHmC2ke9O1QIdge8jLoDcMSh3J742FMVnU7TPnB4RD3AYMt2c5gGez_fGA3pB29wcXCpVm-sJnczgjq5XREGsbkbCsqY8IIDO3VxFC9-llXyqnE-MqYtilfg9HquWEASKB33T0WewwqPSSZA_MVWd74-_NsFAHJPTzsaFYi18Wdo5cid7Hyd5VPBvE0omJEWwORcuZvx_w2yRAonI4qjvEoKj_kCNW-SSpEbv9h5VGSx2hKoj_CRg-s2c3VsYpet23crqAZUl5z9qrfYCe7XTbDJR5wRripzd_mM-gxPdTB2x58DVcXB8dYMHyAko6qgJZwTGYjJM-hU0DVwZyl-V8mVMKl1OtLR-Txa0wfLZxRHouA6-k20hx3wdENhAlZWdX0VPND5KRtkD1Sv8kVGdg0REy6RL9_0id8v4oT_rJqXPJn7uNd3Sd1M_L6oU3Bc0XXB6muA_qHmMm9cusP5LqDyq6R0H5UNYpLtyVjjNZnJGwnlUL4KiS4qLJhcVPW-AaYn2z6VfE2fqtttjgLpci0qZaXFMWYdLR9hyK--oZmfnXUTCavpN7PrJ_jbrm0NfsNFttNPzJCwAUSfmYIOoP3nsApQYxNqiPjhMQ6Sku3Ach7S86f828vYXI8n0rPB084qNl-2Z6ZrbvTeqskyLozDWHl7kSVr6vkCucmRwBb_gUnpyK9vUR6IlRkEAy2py8kDnQ
Exception thrown: 'System.Net.WebException' in System.dll
HTTP: Unauthorized
{
  "error" : "Could not parse auth token."
}

However, If I never try to login using google account, just using facebook account , It can return the valid firebase auth token that I can use.

PS :
One account per email address is enabled
Facebook and google account both using the same email address

Ref :
http://stackoverflow.com/questions/40766312/firebase-overwrites-signin-with-google-account/40768870?noredirect=1#comment68762232_40768870

Google accounts will overwrite all the other account if not linked before.

Need to handle verifyAssertion response if verifiedProvider does not contain providerId and needConfirmation field

Erro To login with user and password

Hi. I didn't get to do this api works with Just user and password authentication.

I try to do with this way;

try{

var config = new FirebaseConfig("my api firebase");
var authProvider = new FirebaseAuthProvider(config);

var retorno = authProvider.SignInWithEmailAndPasswordAsync(user, passwd);

var retornoserver = await retorno;

            return retornoserver.FirebaseToken;

}catch(Exeption e){
retur null;
}

the e is null. I don't know what I am doing wrong. Anybody can help me?

Problem using SignInWithEmailAndPassword

Just starting with Firebase, and discovered your posts and libraries.
When i have my rules set to anonymous access (write and read), i can post to the database.

When i try with a email login, i always get the error: { "error" : "Could not parse auth token." }
auth.user shows the correct email and Id.

This is the code i'm using:

        var firebase = new FirebaseClient(databaseUrl);
        var authProvider = new FirebaseAuthProvider(new FirebaseConfig(apiKey));      

        var auth = await authProvider.SignInWithEmailAndPasswordAsync( xxxx , yyyy );

        var db = firebase
            .Child("SanPrg2")
            .WithAuth( auth.FirebaseToken );

        var d = new Dinosaur { Height = 20 };
        await db.PostAsync(d);

How to get a phone number from the method GetUserAsync?

when authenticating using a phone number, the response from firebase is as follows:

{ "kind": "identitytoolkit#GetAccountInfoResponse", "users": [ { "localId": "xxxxxxxxx", "providerUserInfo": [ { "providerId": "phone", "rawId": "+12345678", "phoneNumber": "+12345678" } ], "lastLoginAt": "1522411438000", "createdAt": "1522323452000", "phoneNumber": "+12345678" } ] }

But User DTO from method GetUserAsync does not contain a phone number.

HTTP proxy auth

Please correspond to HTTP proxy connection.
I want to implement firebase application with proxy.

I need proxy not only authentication but also database and storage.

Thank you.

Next login failed

Hi All!
I need help because I made one console app that start with cron job and every time it call SignInWithEmailAndPasswordAsync function. first call succeess but next fails with this exception:

{"Exception occured while authenticating.\nUrl: https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={0}\nRequest Data: {\"email\":\"[email protected]\",\"password\":\"passwordSubmitted\",\"returnSecureToken\":true}\nResponse: {\n \"error\": {\n \"errors\": [\n {\n \"domain\": \"global\",\n \"reason\": \"invalid\",\n \"message\": \"TOO_MANY_ATTEMPTS_TRY_LATER\"\n }\n ],\n \"code\": 400,\n \"message\": \"TOO_MANY_ATTEMPTS_TRY_LATER\"\n }\n}\n\nReason: Undefined"}

this is my code:

` Firebase.Auth.FirebaseAuth fbAuth = new Firebase.Auth.FirebaseAuth();

                Firebase.Auth.FirebaseAuthProvider fbAuthProvider = new Firebase.Auth.FirebaseAuthProvider(new Firebase.Auth.FirebaseConfig(_apiKey));

                Firebase.Auth.FirebaseAuthLink auth = await fbAuthProvider.SignInWithEmailAndPasswordAsync(_username, _password);

                _fbClient = new Firebase.Database.FirebaseClient(_baseUrl, new Firebase.Database.FirebaseOptions
                {
                    AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken),
                }); `

Is it possible set keepAlive = false?
Thanks in advance.

Issue Auth with email and password or custom token

Hi, I was using this library perfect, but late the library stops working. this is my code:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Firebase.Auth;
using Firebase.Database;
using Firebase.Database.Query;

namespace FireBaseCSharp
{
public class DatosEnvio1800
{
public int CodigoAsistencia { get; set; }
public int CodigoOperador { get; set; }
public int TipoServicio { get; set; }
public int CodUsuExtranet { get; set; }
public int CodLlamada { get; set; }
public string CodigoOperadorFirebase { get; set; }
public int Estado { get; set; }

}

public class Program
{
    private FirebaseAuthProvider _authProvider;
    public static void Main(string[] args)
    {
        try
        {
            new Program().Run().Wait();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message + "----->" + e.InnerException);
            Console.ReadLine();
        }
    }
    private async Task Run()
    {
        /*IFirebaseConfig config = new FirebaseConfig
        {
            AuthSecret = "*************************",
            BasePath = "https://**************.firebaseio.com/"
        };
        IFirebaseClient client = new FirebaseClient(config);
        var datos1800 = new DatosEnvio1800
        {
            CodigoOperadorFirebase = "dLmpI3yKGDYPHl2qPNlnUOA1mkA3",
            CodLlamada = 12,
            CodUsuExtranet = 1154,
            CodigoAsistencia = 12,
            CodigoOperador = 2,
            TipoServicio = 1, //1: Asistencia Casa Habitacion 2: Cita Médica 3: Médico a domicilio 4: Asistencia Vehículo
            Estado = 1, //1: Peticion activa 2: Peticion tomada 3: En espera
        };
        PushResponse response = await client.PushAsync("Asistencias/push", datos1800);*/

        _authProvider = new FirebaseAuthProvider(new FirebaseConfig("********************"));
        
        var mail = "*****@******.com.ec";
        var pass = "**********************************";
        /*var mail = "****@**********.com.ec";
        var pass = "**********************************";*/


        var tokenGenerator = new Firebase.TokenGenerator("*****************");
        var authPayload = new Dictionary<string, object>()
        {
            { "uid", "564987" },
            { "some", "UsuarioCSharp" },
            { "data", "*****@*****************.com.ec" }
        };
        string token = tokenGenerator.CreateToken(authPayload);



        var auth = await _authProvider.SignInWithCustomTokenAsync(token);

        var firebaseClient = new FirebaseClient(
            "https://tecniseguros-1800.firebaseio.com/",
            new FirebaseOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken)
            });


        var datos1800 = new DatosEnvio1800
        {
            CodigoOperadorFirebase = "dLmpI3yKGDYPHl2qPNlnUOA1mkA3",
            CodLlamada = 12,
            CodUsuExtranet = 1154,
            CodigoAsistencia = 12,
            CodigoOperador = 2,
            TipoServicio = 1, //1: Asistencia Casa Habitacion 2: Cita Médica 3: Médico a domicilio 4: Asistencia Vehículo
            Estado = 1, //1: Peticion activa 2: Peticion tomada 3: En espera
        };

        var i = await firebaseClient
            .Child("Asistencias")
            .PostAsync(datos1800);

        
    }
}

}

and this is the error that the catch drops

Se han producido uno o varios errores.----->Firebase.Auth.FirebaseAuthException: Exception occured while authenticating.
Url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key={0}
Request Data: {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ2IjowLCJpYXQiOjE1MjA0MzA2NTYsImQiOnsidWlkIjoiNTY0OTg3Iiwic29tZSI6IlVzdWFyaW9DU2hhcnAiLCJkYXRhIjoiaW5mb0B0ZWNuaXNlZ3Vyb3MuY29tLmVjIn19.ImRvLg5S_Xf4LyWbsTW_flMESrHQBo0D_gsA7NO6dfc","returnSecureToken":true}
Response: N/A
Reason: Undefined ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: No es posible conectar con el servidor remoto ---> System.Net.Sockets.SocketException: Intento de acceso a un socket no permitido por sus permisos de acceso 172.217.3.74:443
en System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
en System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- Fin del seguimiento de la pila de la excepción interna ---
en System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
en System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
--- Fin del seguimiento de la pila de la excepción interna ---
en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
en System.Net.Http.HttpClient.d__58.MoveNext()
--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
en Firebase.Auth.FirebaseAuthProvider.d__31.MoveNext()
--- Fin del seguimiento de la pila de la excepción interna ---
en Firebase.Auth.FirebaseAuthProvider.d__31.MoveNext()
--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---
en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
en Firebase.Auth.FirebaseAuthProvider.d__13.MoveNext()

can you help me please with this issue?

Refreshing auth token

I have windows application that is needed to run all time. I have implemented following code to sign in:
`auth = await authProvider.SignInWithEmailAndPasswordAsync(username, password);
auth.FirebaseAuthRefreshed += (s, e) => saveAuth(e.FirebaseAuth);

dbClient = new FirebaseClient(url, new FirebaseOptions
{
OfflineDatabaseFactory = (t, s) => new OfflineDatabase(t, s),
AuthTokenAsyncFactory = async () => (await auth.GetFreshAuthAsync()).FirebaseToken
});`

Ocassionally I still get a unauthorized expection:
step-up-labs/firebase-database-dotnet#87

What is the possible reason for this?

Refresh auth after expiration

When i leave my app open for a long time, i start getting "auth token expired" -responses from firebase.
Is there a way to use the RefreshToken for refreshing the FirebaseToken, or should i just call a SignIn.. method again before ExpresIn?

Unable to sign in

Client pc cannot sign in. Gets this expection:
Exception occured while authenticating.
Url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={0}
Request Data: {"email":"[email protected]","password":"password","returnSecureToken":true}
Response: N/A
Reason: Undefined

Same app, configuration signs in normally on another pc on another network. What is the possible cause of expection? Could this be maybe fixed by demanding ports 5228, 5229, 5230 to be opened by network admin?

GetUserAsync hangs up when passed incorrect token

Not for all request the email address and password can be sent to verify and work accordingly. So the generated token is what to be used after a successful login. But using the GetUserAsync and passing a wrong token hangs up. Does not do anything and just holds on that position. No exception even.
Am I missing something?

SignInWithIdTokenAsync function using rest api?

do you know if it is possible to do signInWithCredential function as described in the link below? because i am using your library for xamarin and mostly it works in the shared .net standard library but google sign in has exception, because google native sigin doesnt return actual access token but it returns an IdToken as jwt form created by google. I couldnt find a possibility to signin into firebase using this this IdToken, i am not sure if customtoken can work.

https://firebase.google.com/docs/auth/android/google-signin

how can I get user uid from firebase after create new user

I am using this code to create user and it works fine (using Visual Studio C# desktop application)

            var authProvider = new FirebaseAuthProvider(new FirebaseConfig("Firebaseapikey"));
            var auth = await authProvider.CreateUserWithEmailAndPasswordAsync("[email protected]", "123456");

but how can I get user UID after create the new user, and is their onsuccess or onerror to that I can use to check if user created or something went wrong like the email is used before

Freezes when used with web api

Initializing Firebase client as follow makes browser freeze, but works great in console. help.

var NewFirebaseClient = new FirebaseClient
(
this.MyFirebaseDatabaseUrl,

                    new FirebaseOptions
                    {
                        AuthTokenAsyncFactory = () => LoginAsync()
                    }
            );

Login credentials are logged to console on authentication failure

If the firebase authentication fails, a FirebaseAuthException is thrown. On some runtimes, like Xamarin, thrown exceptions are being logged to the console.
A FirebaseAuthException contains the whole Request and Response and compiles them into the exception message. However, at least the request, possibly the response contains sensitive information, which should not appear in a system-wide log. Therefore, the FirebaseAuthException should not include it in it's Message.

Help with Library...

Hello,

I downloaded the library but the project will not load. I am using Visual Studio 2015.

WHat I need to do is VERY simple. I just need to have the ability to update one value in our Firebase DB from our website. We have written and iOS app that uses Firebase and talks to our back end server. I am a bit rusty with my C# and cannot figure out how to use your library. I tried implementing your example code, but it will not compile. The editor complains and shows errors.

I am trying to simply log into Firebase using an account we created and then update one value, but I cannot figure out how to use your library to log in... haven't even gotten to attempt to update the value.

Any help would be greatly appreciated as I have been toying around for two days with your lib.

Using your code snippet from the site on my system the compiler complains about this:

auth.FirebaseToken

auth does not have a FirebaseToken property. That is one one a few errors I am getting. Another is that my VS does not like await. Again, I am very rusty with my c# as I have been doing iOS development for some years now and not much c#. May questions and issues may seem foolish, but I cannot figure it out.

Thank you for any help!!!!

Documentation or Examples on How to Use this Library

I have created a C# wrapper over Firebase API for using basic CRUD commands. Everything works great. Now I need to retrieve the users Firebase Authentication "User UID" using the users email address and password that is associated with the "User UID". From the description that you posted regarding you library it looks like I might be able to accomplish this bit of code. Do you have any documentation, tutorials or examples on how to inject your library into my C# .Net application and utilize the functions?

Any help would be greatly appreciated. Thanks. John

how to check if user token already exists before signin anonymously ?

For the moment I use the "official" Xamarin.FirebaseAuth wrapper on Android. To sign in I do

auth = FirebaseAuth.Instance;
auth.AuthState += AuthStateChanged;
void AuthStateChanged(object sender, FirebaseAuth.AuthStateEventArgs e)
        {
            user = e.Auth.CurrentUser;
            if (user == null)
            {
                SignInAnonymously();
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("User already signed in ! User : " + user.Uid);
            }
        }

I would like to switch to your plugin. But how to know if the user already exists and in this case how to retrieve the user information ?

provider.SignInWithOAuth() throws exception.

Exception: "Response status code does not indicate success: 400" when I call SignInWithOAuth
var auth = await provider.SignInWithOAuthAsync(FirebaseAuthType.Facebook, facebookAccessToken);
The facebookAccessToken is generated properly and I use Firebase Browser APIKey for FirebaseConfig
UWP 10.0

Stack trace:
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode() at Firebase.Auth.FirebaseAuthProvider.<SignInWithPostContentAsync>d__16.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable``1.ConfiguredTaskAwaiter.GetResult() at Firebase.Auth.FirebaseAuthProvider.<SignInWithOAuthAsync>d__8.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter``1.GetResult() at simple_social_media.MainPage.<mainlogin_Click>d__1.MoveNext()

Could the problem be at my end?

Cannot install

I cannot install this package, I have tried .net 2.0 and .net 4.5

Install-Package : Could not install package 'FirebaseAuthentication.net 3.0.5'. You are trying to install this package into a project that targets '.NETFramework,Version=v2.0',
but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
At line:1 char:16

  • Install-Package <<<< FirebaseAuthentication.net
    • CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
    • FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

Install-Package : Could not install package 'FirebaseAuthentication.net 3.0.5'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5',
but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
At line:1 char:16

  • Install-Package <<<< FirebaseAuthentication.net
    • CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
    • FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

Troubles with authorization

I'm having troubles authorizing requests to a firebase db. I have been able to authenticate with a simple account with user and password, as following:

var authProvider = new FirebaseAuthProvider(new FirebaseConfig(firebaseApiKey));
var auth = await authProvider.SignInWithEmailAndPasswordAsync("[email protected]", "password");

After I retrieve the Firebase Token, I pass it along to the FireBase client constructor as described in documentation, and i'm trying to make requests:

var firebaseClient = new FirebaseClient("https://[DB].firebaseio.com/", new FirebaseOptions
{
    AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken)
});
var groups = await firebaseClient.Child("groups").OnceAsync<dynamic>();

A request like this is sent to the server (i'm using fiddler to observe what happens behind the curtains):

GET https://[DB].firebaseio.com/groups/.json?auth=[TOKEN] HTTP/1.1
Connection: Keep-Alive
Host: settle-up-live.firebaseio.com

However i keep getting 401 responses, like the following:

HTTP/1.1 401 Unauthorized
Server: nginx
Date: Tue, 20 Feb 2018 20:02:32 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 36
Connection: keep-alive
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Strict-Transport-Security: max-age=31556926; includeSubDomains; preload

{
  "error" : "Permission denied"
}

For the record, i'm querying the Settle Up firebase DB, also from Step Up Labs.

DeleteUser not found

I can't seem to find the DeleteUser(string idToken) method inside FirebaseAuthProvider. Any reason for it?

how to sign out?

I dont see any sign out function in the library and also firebase rest api documentation doesnt have it. I wonder how should we handle sign out cases?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.