Example #1
0
        public async Task <UserGitHubAccountView> GetUserDataFirebaseByToken(string token)
        {
            GoogleCredential credential;

            using (var stream = new FileStream("TestAuth-8cb3dbdbce24.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream);
            }

            FirebaseApp defaultApp;

            if (FirebaseApp.DefaultInstance == null)
            {
                defaultApp = FirebaseApp.Create(new AppOptions()
                {
                    Credential = credential
                });
            }
            else
            {
                defaultApp = FirebaseApp.DefaultInstance;
            }

            var auth     = FirebaseAuth.GetAuth(defaultApp);
            var userData = await auth.VerifyIdTokenAsync(token);

            var result = new UserGitHubAccountView()
            {
                Name  = userData.Claims["name"].ToString(),
                Email = userData.Claims["email"].ToString()
            };

            return(result);
        }
Example #2
0
        private void InitializeAuthService(IServiceCollection services)
        {
            var path = Configuration.GetSection("FirebaseApi").GetValue <string>("CredentialFilePath");

            JToken jAppSettings = JToken.Parse(
                File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "appsettings.json"))
                );


            string mapping = jAppSettings["GoogleCredentials"].ToString();


            // Initialize the default app
            var defaultApp = FirebaseApp.Create(new AppOptions()
            {
                //Credential = GoogleCredential.FromFile(path)
                Credential = GoogleCredential.FromJson(mapping)
            });

            Console.WriteLine(defaultApp.Name); // "[DEFAULT]"

            // Retrieve services by passing the defaultApp variable...
            var defaultAuth = FirebaseAuth.GetAuth(defaultApp);

            // ... or use the equivalent shorthand notation
            //defaultAuth = FirebaseAuth.DefaultInstance;

            services.AddSingleton(defaultAuth);

            services.AddSingleton <IAuthService, FirebaseAuthService>();
        }
Example #3
0
        // Handle initialization of the necessary firebase modules:
        protected void InitializeFirebase()
        {
            DebugLog("Setting up Firebase Auth");
            auth = FirebaseAuth.DefaultInstance;
            auth.StateChanged   += AuthStateChanged;
            auth.IdTokenChanged += IdTokenChanged;
            // Specify valid options to construct a secondary authentication object.
            if (otherAuthOptions != null &&
                !(string.IsNullOrEmpty(otherAuthOptions.ApiKey) ||
                  string.IsNullOrEmpty(otherAuthOptions.AppId) ||
                  string.IsNullOrEmpty(otherAuthOptions.ProjectId)))
            {
                try
                {
                    otherAuth = FirebaseAuth.GetAuth(FirebaseApp.Create(
                                                         otherAuthOptions, "Secondary"));
                    otherAuth.StateChanged   += AuthStateChanged;
                    otherAuth.IdTokenChanged += IdTokenChanged;
                }
                catch (Exception)
                {
                    DebugLog("ERROR: Failed to initialize secondary authentication object.");
                }
            }

            AuthStateChanged(this, null);
        }
Example #4
0
 private void InitializeAuth()
 {
     _auth = FirebaseAuth.GetAuth(_app);
     _auth.StateChanged += OnAuthStateChanged;
     OnAuthStateChanged(this, null);
     _app.Options.DatabaseUrl = new Uri("https://unit-man-default-rtdb.firebaseio.com/");
 }
    void LogFirebaseReconnect()
    {
        string username = GameManager.Instance.GetUserID();

        username = username + "@evolution.com";
        string password = "******";

        FirebaseAuth.DefaultInstance.SignInWithEmailAndPasswordAsync(username, password).ContinueWith((obj) =>
        {
            if (obj.IsFaulted) //El usuario no se ha registrado.
            {
                FirebaseAuth.GetAuth(FirebaseApp.DefaultInstance).CreateUserWithEmailAndPasswordAsync(username, password).ContinueWith(task =>
                {
                    if (task.IsCompleted)
                    {
                        print("Te has reconectado");
                    }

                    if (task.IsFaulted)
                    {
                        Message.Instance.NewMessage("Firebase no conecta");
                        SceneManager.LoadScene(0); //Recargar la escena y volver a intentar
                    }
                });
            }
            else
            {
                print("Te has reconectado");
            }
        });
    }
        public async Task CreateCustomTokenWithoutServiceAccount()
        {
            var googleCred  = FirebaseApp.DefaultInstance.Options.Credential;
            var serviceAcct = (ServiceAccountCredential)googleCred.UnderlyingCredential;
            var token       = await((ITokenAccess)googleCred).GetAccessTokenForRequestAsync();
            var app         = FirebaseApp.Create(
                new AppOptions()
            {
                Credential       = GoogleCredential.FromAccessToken(token),
                ServiceAccountId = serviceAcct.Id,
            }, "IAMSignApp");

            try
            {
                var customToken = await FirebaseAuth.GetAuth(app).CreateCustomTokenAsync(
                    "testuser");

                var idToken = await SignInWithCustomTokenAsync(customToken);

                var decoded = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken);

                Assert.Equal("testuser", decoded.Uid);
            }
            finally
            {
                app.Delete();
            }
        }
Example #7
0
        internal static void InitCustomApp()
        {
            var defaultOptions = new AppOptions()
            {
                Credential = GoogleCredential.GetApplicationDefault(),
            };
            var otherAppConfig = new AppOptions()
            {
                Credential = GoogleCredential.GetApplicationDefault(),
            };

            // [START access_services_nondefault]
            // Initialize the default app
            var defaultApp = FirebaseApp.Create(defaultOptions);

            // Initialize another app with a different config
            var otherApp = FirebaseApp.Create(otherAppConfig, "other");

            Console.WriteLine(defaultApp.Name); // "[DEFAULT]"
            Console.WriteLine(otherApp.Name);   // "other"

            // Use the shorthand notation to retrieve the default app's services
            var defaultAuth = FirebaseAuth.DefaultInstance;

            // Use the otherApp variable to retrieve the other app's services
            var otherAuth = FirebaseAuth.GetAuth(otherApp);
            // [END access_services_nondefault]
        }
Example #8
0
        public void init()
        {
            ClientSecrets cs = new ClientSecrets();

            cs.ClientId     = "";
            cs.ClientSecret = "";
            //GoogleClientSecrets
            //var fa = FirebaseAuth.DefaultInstance();
            //GoogleWebAuthorizationBroker.AuthorizeAsync(cs,
            //    new[] { DriveService.Scope.Drive},
            //        "user",
            //        )
            // Initialize the default app
            var cre = GoogleCredential.FromFile(@"C:\Users\Onsiter\Downloads\google-services.json");

            var appOpt = new AppOptions();

            appOpt.ProjectId        = "testfirebase-18749";
            appOpt.ServiceAccountId = "";
            appOpt.Credential       = cre;
            var defaultApp = FirebaseApp.Create(appOpt);

            Console.WriteLine(defaultApp.Name); // "[DEFAULT]"

            // Retrieve services by passing the defaultApp variable...
            var defaultAuth = FirebaseAuth.GetAuth(defaultApp);

            // ... or use the equivalent shorthand notation
            defaultAuth = FirebaseAuth.DefaultInstance;
        }
        // 推播訊息的Json格式範例
        //{
        //    "multicast_id": 7707128547180318330,
        //    "success": 0,
        //    "failure": 1,
        //    "canonical_ids": 0,
        //    "results": [
        //        {
        //            "error": "NotRegistered"
        //        }
        //    ]
        //}

        public void Awake()
        {
            const string credentialFileName = "serviceAccountKey.json";

            // 讀取憑證文件並產生憑證物件
            GoogleCredential googleCredential = null;

            string[] paths = new string[]
            {
                Path.Combine("..", "Config", "Key", credentialFileName),
                Path.Combine("..", "..", "Config", "Key", credentialFileName)
            };
            string path = paths.FirstOrDefault(e => File.Exists(e));

            if (string.IsNullOrEmpty(path))
            {
                Log.Error($"GoogleCredential 's serviceAccountKey.json doesnt exist on the path!");
                return;
            }
            else
            {
                googleCredential = GoogleCredential.FromFile(path);
            }

            // 產生FirebaseApp實體
            firebaseApp = FirebaseApp.Create(new AppOptions()
            {
                Credential = googleCredential,
            });

            // 產生FirebaseMessaging實體
            firebaseMessaging = FirebaseMessaging.GetMessaging(firebaseApp);

            firebaseAuth = FirebaseAuth.GetAuth(firebaseApp);
        }
Example #10
0
        private void OnEnable()
        {
            bool isEditor = false;

#if UNITY_EDITOR
            isEditor = true;
#endif

            if (isEditor)
            {
                FirebaseApp firebaseApp = FirebaseApp.Create(
                    FirebaseApp.DefaultInstance.Options,
                    "FIREBASE_EDITOR");

                firebaseApp.SetEditorDatabaseUrl("https://artie-data.firebaseio.com/");

                FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
                {
                    if (task.Result == DependencyStatus.Available)
                    {
                        _dbReference   = FirebaseDatabase.GetInstance(firebaseApp).RootReference;
                        _storage       = FirebaseStorage.GetInstance(firebaseApp);
                        _auth          = FirebaseAuth.GetAuth(firebaseApp);
                        _phoneProvider = PhoneAuthProvider.GetInstance(_auth);
                        _functions     = FirebaseFunctions.DefaultInstance;
                        if (localServices.Value)
                        {
                            _functions.UseFunctionsEmulator("http://localhost:5001");
                        }

                        // Listener for authentications changes
                        _auth.StateChanged += this.AuthStateChanged;
                        AuthStateChanged(this, null);
                    }
                    else
                    {
                        Debug.LogError("Could not resolve all Firebase dependencies: " + task.Result);
                        Console.WriteLine("Could not resolve all Firebase dependencies: " + task.Result);

                        // Listener for authentications changes
                        _auth.StateChanged += this.AuthStateChanged;
                        AuthStateChanged(this, null);
                    }
                });
            }
            else
            {
                FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://artie-data.firebaseio.com/");
                _dbReference   = FirebaseDatabase.DefaultInstance.RootReference;
                _storage       = FirebaseStorage.DefaultInstance;
                _functions     = Firebase.Functions.FirebaseFunctions.DefaultInstance;
                _auth          = FirebaseAuth.DefaultInstance;
                _phoneProvider = PhoneAuthProvider.GetInstance(_auth);

                // Listener for authentications changes
                _auth.StateChanged += this.AuthStateChanged;
                AuthStateChanged(this, null);
            }
        }
Example #11
0
 public FirebaseAuthManagement()
 {
     App = FirebaseApp.Create(new AppOptions()
     {
         Credential = GoogleCredential.GetApplicationDefault()
     });
     auth = FirebaseAuth.GetAuth(App);
 }
Example #12
0
        public FirebaseAuthProvider(FirebaseAuthConfiguration configuration)
        {
            configuration.ShouldNotBeNull();

            var app = FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromJson(configuration.ServiceAccountJson)
            });

            _auth = FirebaseAuth.GetAuth(app);
        }
Example #13
0
    }                           // Empty function to wake up the object

    void Awake()
    {
        #if UNITY_EDITOR
        auth = FirebaseAuth.GetAuth(FirebaseManager.Instance.App);
        SignIn("*****@*****.**", "testingtesting123", () => {}, error => {});
        #else
        auth = FirebaseAuth.DefaultInstance;
        #endif

        auth.StateChanged += AuthStateChanged;
        AuthStateChanged(this, null);
    }
Example #14
0
		public async Task<string> CreateResponderCustomAuthToken(string userId, Dictionary<string, object> claims = null)
		{
			CreateResponderInstance();

			if (_responderFirebaseApp != null)
			{
				string customToken = await FirebaseAuth.GetAuth(_responderFirebaseApp).CreateCustomTokenAsync(userId, claims);
				return customToken;
			}

			return "";
		}
        public void GetAuth()
        {
            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential = MockCredential
            }, "MyApp");
            FirebaseAuth auth = FirebaseAuth.GetAuth(app);

            Assert.Same(auth, FirebaseAuth.GetAuth(app));
            app.Delete();
            Assert.Throws <InvalidOperationException>(() => FirebaseAuth.GetAuth(app));
        }
Example #16
0
 private async Task <FirebaseToken> isGoogleIdTokenValid(string idToken)
 {
     try
     {
         return(await FirebaseAuth.GetAuth(Startup.FirebaseApp)
                .VerifyIdTokenAsync(idToken));
     }
     catch (FirebaseAuthException)
     {
         return(null);
     }
 }
Example #17
0
        public void CreateFirebaseApp(string keyPath)
        {
            if (keyPath != _keyPath)
            {
                firebaseApp = FirebaseApp.Create(new AppOptions
                {
                    Credential = GoogleCredential.FromFile(keyPath)
                });

                firebaseAuth = FirebaseAuth.GetAuth(firebaseApp);
                _keyPath     = keyPath;
            }
        }
Example #18
0
        public async Task <LoginResultApiModel> LogInAsync(string firebaseToken, string phoneNumber)
        {
            var auth = FirebaseAuth.GetAuth(FirebaseApp.DefaultInstance);

            //this can throw detailed error message.
            var verified = await auth.VerifyIdTokenAsync(firebaseToken);

            var identityUser = await usersRepository.GetByIdAsync(verified.Uid);

            //user confirmed his phone number, but has not registered yet;
            //Register him now in that case

            var isNewUser = false;

            if (identityUser == null)
            {
                try
                {
                    var username = "******" + Guid.NewGuid();

                    identityUser = await RegisterNewUserAsync(new RegisterModel
                    {
                        PhoneNumber = phoneNumber,
                        UserName    = username,
                        Id          = verified.Uid
                    });

                    isNewUser = true;
                }
                catch (Exception ex)
                {
                    throw new InvalidDataException("Couldn't register this user.", ex);
                }
            }
            else
            {
                if (identityUser.PhoneNumber != phoneNumber)
                {
                    throw new UnauthorizedAccessException("Please provide a phone number that correlates to firebase JWT token.");
                }
            }

            return(new LoginResultApiModel
            {
                Info = identityUser.ToAppUserDto(),
                Token = tokenGenerator.GenerateToken(identityUser),
                RefreshToken = identityUser.RefreshToken,
                IsNewUser = isNewUser
            });
        }
Example #19
0
        private Logger logger = null;                           // Logger 物件


        private FireBaseHandler()
        {
            try
            {
                FirebaseApp defaultApp = FirebaseApp.Create(new AppOptions()
                {
                    Credential = GoogleCredential.FromFile(keyPath),
                });

                authInstance = FirebaseAuth.GetAuth(defaultApp);
            }
            catch (Exception ex)
            {
                SaveLog($"[Error] FireBaseHandler::FireBaseHandler, Catch Error, Msg:{ex.Message}");
            }
        }
Example #20
0
        public AuthService(IOptions <FirebaseConfig> firebaseConfig)
        {
            _firebaseConfig = firebaseConfig;
            var firebaseCredentials = _firebaseConfig.Value.Credentials;

            if (firebaseCredentials == string.Empty)
            {
                throw new Exception("Firebase cedentials missing");
            }
            var fb = FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromJson(firebaseCredentials)
            });

            _firebase = FirebaseAuth.GetAuth(fb);
        }
Example #21
0
        public static void Send(string token, string title, string body, string link = "")
        {
            try
            {
                var defaultApp = FirebaseApp.Create(new AppOptions()
                {
                    Credential = GoogleCredential.FromFile(HostingEnvironment.ApplicationPhysicalPath + @"\assets\anbarii-firebase-adminsdk-rh9du-ab014d04e2.json"),
                });
                Console.WriteLine(defaultApp.Name); // "[DEFAULT]"

                // Retrieve services by passing the defaultApp variable...
                var defaultAuth = FirebaseAuth.GetAuth(defaultApp);

                // ... or use the equivalent shorthand notation
                defaultAuth = FirebaseAuth.DefaultInstance;
            }
            catch { }
            var message = new Message()
            {
                Notification = new Notification()
                {
                    Title = title,
                    Body  = body,
                },
                Webpush = new WebpushConfig()
                {
                    Headers = new Dictionary <string, string>()
                    {
                        { "Urgency", "high" },
                    },
                    Notification = new WebpushNotification()
                    {
                        Title = title,
                        Body  = body,
                    },
                    FcmOptions = new WebpushFcmOptions()
                    {
                        Link = link
                    },
                },
                Token = token,
            };

            FirebaseMessaging.DefaultInstance.SendAsync(message);
            // Response is a message ID string.
        }
Example #22
0
        internal static void InitDefaultApp()
        {
            // [START access_services_default]
            // Initialize the default app
            var defaultApp = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.GetApplicationDefault(),
            });

            Console.WriteLine(defaultApp.Name); // "[DEFAULT]"

            // Retrieve services by passing the defaultApp variable...
            var defaultAuth = FirebaseAuth.GetAuth(defaultApp);

            // ... or use the equivalent shorthand notation
            defaultAuth = FirebaseAuth.DefaultInstance;
            // [END access_services_default]
        }
Example #23
0
        public async Task <bool> DeleteUser(string id)
        {
            var auth = FirebaseAuth.GetAuth(this.firebase);

            await _userDao.DeleteUser(id);

            try
            {
                await auth.GetUserAsync(id); // If the user does not exist an exception is thrown

                await auth.DeleteUserAsync(id);
            }
            catch (FirebaseAuthException)
            {
                throw new GrooverException("The user specified does not exists", 400);
            }

            return(true);
        }
Example #24
0
        private bool ValidateToken(HttpRequestHeaders header)
        {
            try
            {
                string token = string.Empty;
                IEnumerable <string> authzHeaders;
                if (!header.TryGetValues("Authorization", out authzHeaders) || authzHeaders.Count() > 1)
                {
                    return(false);
                }

                BearerToken1 = authzHeaders.ElementAt(0);
                token        = BearerToken1.StartsWith("Bearer ") ? BearerToken1.Substring(7) : BearerToken1;


                var         credentials = GoogleCredential.FromFile(ConfigurationManager.AppSettings["GOOGLE_APPLICATION_CREDENTIALS"]);
                FirebaseApp defaultApp  = null;
                try
                {
                    defaultApp = FirebaseApp.Create(new AppOptions()
                    {
                        Credential = credentials
                    });
                }
                catch (Exception)
                {
                    defaultApp = FirebaseApp.DefaultInstance;
                }

                var defaultAuth = FirebaseAuth.GetAuth(defaultApp);
                defaultAuth = FirebaseAuth.DefaultInstance;
                FirebaseToken decodedToken = defaultAuth.VerifyIdTokenAsync(token).Result;

                string uid = decodedToken.Uid;
                return(true);
            }
            catch (Exception ex)
            {
                log.EscribirLogError("Error durante la validación de token", ex);
                return(false);
            }
        }
Example #25
0
        public AuthService(IConfiguration configuration, IUserService userService, ILogger <AuthService> logger)
        {
            _configuration = configuration;
            _userService   = userService;
            _logger        = logger;

            var firebaseCredentials = _configuration["Firebase:Credentials"];

            if (firebaseCredentials == string.Empty)
            {
                throw new Exception("Firebase cedentials missing");
            }

            var fb = FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromJson(firebaseCredentials)
            });

            _firebase = FirebaseAuth.GetAuth(fb);
        }
Example #26
0
        public async Task <string> GenerateToken(UserInfo userData, IAuthResponse credentials)
        {
            var auth = FirebaseAuth.GetAuth(this.firebase);

            try
            {
                await auth.GetUserAsync(userData.Id); // If the user does not exist an exception is thrown

                await auth.UpdateUserAsync(new UserRecordArgs()
                {
                    Email       = userData.Email,
                    DisplayName = userData.Display_name,
                    Uid         = userData.Id,
                    PhotoUrl    = userData.Images.FirstOrDefault()?.Url
                });
            }
            catch (FirebaseAuthException)
            {
                await auth.CreateUserAsync(new UserRecordArgs()
                {
                    Email       = userData.Email,
                    DisplayName = userData.Display_name,
                    Uid         = userData.Id,
                    PhotoUrl    = userData.Images.FirstOrDefault()?.Url
                });
            }
            var user = new Entities.Application.User(userData, credentials.Access_token, credentials.Expires_in, DateTime.UtcNow);

            if (!string.IsNullOrEmpty(credentials.Refresh_Token))
            {
                user.RefreshToken = credentials.Refresh_Token;
            }
            await this.CreateOrUpdateUser(user);

            var token = await auth.CreateCustomTokenAsync(user.Id);

            return(token);
        }
Example #27
0
        private async Task <string> GenerateToken(UserInfo userData, IAuthResponse credentials)
        {
            var auth = FirebaseAuth.GetAuth(firebaseApp);

            try
            {
                await auth.GetUserAsync(userData.Id); // If the user does not exist an exception is thrown

                await auth.UpdateUserAsync(new UserRecordArgs()
                {
                    Email       = userData.Email,
                    DisplayName = userData.Display_name,
                    Uid         = userData.Id,
                    PhotoUrl    = userData.Images.FirstOrDefault()?.Url
                });
            }
            catch (FirebaseAuthException)
            {
                await auth.CreateUserAsync(new UserRecordArgs()
                {
                    Email       = userData.Email,
                    DisplayName = userData.Display_name,
                    Uid         = userData.Id,
                    PhotoUrl    = userData.Images.FirstOrDefault()?.Url
                });
            }
            // var user = new User(userData, credentials.Access_token, credentials.Expires_in, DateTime.UtcNow);
            var reference = firestoreDb.Collection("users").Document($"{userData.Id}");
            //if ((await reference.GetSnapshotAsync()).Exists)
            //    await reference.UpdateAsync(user.ToDictionary());
            //else
            //    await reference.CreateAsync(user.ToDictionary());

            var token = await auth.CreateCustomTokenAsync(userData.Id);

            return(token);
        }
Example #28
0
 private async Task <string> CreateCustomTokenAsync(string id)
 {
     return(await FirebaseAuth.GetAuth(_firebaseContext.App).CreateCustomTokenAsync(id));
 }
            public override TenantAwareFirebaseAuth AuthFromApp(FirebaseApp app)
            {
                var auth = FirebaseAuth.GetAuth(app);

                return(auth.TenantManager.AuthForTenant(this.Auth.TenantId));
            }
 public FirebaseTokenVerifier(FirebaseApp firebaseApp)
 {
     _firebaseApp = _firebaseApp = FirebaseAuth.GetAuth(firebaseApp);
 }