Esempio n. 1
0
        internal async Task <string> CreateSessionCookieAsync(
            string idToken,
            SessionCookieOptions options,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(idToken))
            {
                throw new ArgumentException("idToken must not be null or empty");
            }

            var validOptions = options.ThrowIfNull(nameof(options)).CopyAndValidate();
            var request      = new Dictionary <string, object>()
            {
                { "idToken", idToken },
                { "validDuration", (long)validOptions.ExpiresIn.TotalSeconds },
            };
            var response = await this.PostAndDeserializeAsync <JObject>(
                ":createSessionCookie", request, cancellationToken).ConfigureAwait(false);

            if (response.Result == null || (string)response.Result["sessionCookie"] == null)
            {
                throw UnexpectedResponseException("Failed to generate session cookie");
            }

            return((string)response.Result["sessionCookie"]);
        }
Esempio n. 2
0
            // [END session_clear_and_revoke]

            internal async Task <ActionResult> CheckAuthTime(string idToken)
            {
                // [START check_auth_time]
                // To ensure that cookies are set only on recently signed in users, check auth_time in
                // ID token before creating a cookie.
                var decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken);

                var authTime = new DateTime(1970, 1, 1).AddSeconds(
                    (long)decodedToken.Claims["auth_time"]);

                // Only process if the user signed in within the last 5 minutes.
                if (DateTime.UtcNow - authTime < TimeSpan.FromMinutes(5))
                {
                    var options = new SessionCookieOptions()
                    {
                        ExpiresIn = TimeSpan.FromDays(5),
                    };
                    var sessionCookie = await FirebaseAuth.DefaultInstance.CreateSessionCookieAsync(
                        idToken, options);

                    // Set cookie policy parameters as required.
                    this.Response.Cookies.Append("session", sessionCookie);
                    return(this.Ok());
                }

                // User did not sign in recently. To guard against ID token theft, require
                // re-authentication.
                return(this.Unauthorized("Recent sign in required"));
                // [END check_auth_time]
            }
Esempio n. 3
0
            public async Task <ActionResult> Login([FromBody] LoginRequest request)
            {
                // Set session expiration to 5 days.
                var options = new SessionCookieOptions()
                {
                    ExpiresIn = TimeSpan.FromDays(5),
                };

                try
                {
                    // Create the session cookie. This will also verify the ID token in the process.
                    // The session cookie will have the same claims as the ID token.
                    var sessionCookie = await FirebaseAuth.DefaultInstance
                                        .CreateSessionCookieAsync(request.IdToken, options);

                    // Set cookie policy parameters as required.
                    var cookieOptions = new CookieOptions()
                    {
                        Expires  = DateTimeOffset.UtcNow.Add(options.ExpiresIn),
                        HttpOnly = true,
                        Secure   = true,
                    };
                    this.Response.Cookies.Append("session", sessionCookie, cookieOptions);
                    return(this.Ok());
                }
                catch (FirebaseAuthException)
                {
                    return(this.Unauthorized("Failed to create a session cookie"));
                }
            }
Esempio n. 4
0
        public IActionResult LogInPOST()
        {
            string email    = Request.Form["email"];
            string password = Request.Form["password"];

            string idTokenOrError = FirebaseAuthHelper.SignInWithEmailAndPassword(email, password);
            string idToken;

            if (idTokenOrError.StartsWith("error: "))
            {
                JObject errorJObject = JObject.Parse(idTokenOrError.Remove(0, 7));
                return(Content(FirebaseAuthHelper.GenerateNiceErrorMessage(errorJObject["message"].ToString())));
            }
            else
            {
                idToken = idTokenOrError.Remove(0, 9);
            }

            TimeSpan expirationTimeSpan;

            if (Request.Form["remember-me"] == "on")
            {
                expirationTimeSpan = TimeSpan.FromDays(14);
            }
            else
            {
                expirationTimeSpan = TimeSpan.FromDays(1);
            }

            SessionCookieOptions options = new SessionCookieOptions()
            {
                ExpiresIn = expirationTimeSpan
            };

            try
            {
                string sessionCookie = FirebaseAuth.DefaultInstance.CreateSessionCookieAsync(idToken, options).Result;

                CookieOptions cookieOptions = new CookieOptions()
                {
                    Expires  = DateTimeOffset.UtcNow.Add(options.ExpiresIn),
                    HttpOnly = true,
                    Secure   = EnvironmentHelper.KeepCookiesSecure()
                };

                Response.Cookies.Append("authSession", sessionCookie, cookieOptions);
                return(Content("success"));
            }
            catch (FirebaseAuthException)
            {
                return(Content("Error: Failed to create a session cookie."));
            }
        }
        public async Task SessionCookie()
        {
            var customToken = await FirebaseAuth.DefaultInstance.CreateCustomTokenAsync("testuser");

            var idToken = await SignInWithCustomTokenAsync(customToken);

            var options = new SessionCookieOptions()
            {
                ExpiresIn = TimeSpan.FromHours(1),
            };
            var sessionCookie = await FirebaseAuth.DefaultInstance.CreateSessionCookieAsync(
                idToken, options);

            var decoded = await FirebaseAuth.DefaultInstance.VerifySessionCookieAsync(sessionCookie);

            Assert.Equal("testuser", decoded.Uid);

            await Task.Delay(1000);

            await FirebaseAuth.DefaultInstance.RevokeRefreshTokensAsync("testuser");

            decoded = await FirebaseAuth.DefaultInstance.VerifySessionCookieAsync(sessionCookie);

            Assert.Equal("testuser", decoded.Uid);

            var exception = await Assert.ThrowsAsync <FirebaseAuthException>(
                async() => await FirebaseAuth.DefaultInstance.VerifySessionCookieAsync(
                    sessionCookie, true));

            Assert.Equal(ErrorCode.InvalidArgument, exception.ErrorCode);
            Assert.Equal(AuthErrorCode.RevokedSessionCookie, exception.AuthErrorCode);

            idToken = await SignInWithCustomTokenAsync(customToken);

            sessionCookie = await FirebaseAuth.DefaultInstance.CreateSessionCookieAsync(
                idToken, options);

            decoded = await FirebaseAuth.DefaultInstance.VerifySessionCookieAsync(sessionCookie, true);

            Assert.Equal("testuser", decoded.Uid);
        }
Esempio n. 6
0
        public IActionResult RegisterPOST()
        {
            string email    = Request.Form["email"];
            string password = Request.Form["password"];

            UserRecordArgs userRecordArgs = new UserRecordArgs
            {
                Email         = email,
                EmailVerified = false,
                Password      = password,
                Disabled      = false
            };

            UserRecord userRecord;

            try
            {
                userRecord = FirebaseAuth.DefaultInstance.CreateUserAsync(userRecordArgs).Result;
            }
            catch (Exception e)
            {
                if (e is ArgumentException)
                {
                    return(Content("Invalid email or password. Your password may be too weak."));
                }

                if (e is FirebaseAuthException firebaseAuthException)
                {
                    return(Content(FirebaseAuthHelper.GenerateNiceErrorMessage(firebaseAuthException.AuthErrorCode)));
                }

                if (e is AggregateException aggregateException)
                {
                    foreach (Exception exception in aggregateException.InnerExceptions)
                    {
                        if (exception is ArgumentException)
                        {
                            return(Content("Invalid email or password. Your password may be too weak."));
                        }

                        if (exception is FirebaseAuthException aggregateFirebaseAuthException)
                        {
                            return(Content(FirebaseAuthHelper.GenerateNiceErrorMessage(aggregateFirebaseAuthException.AuthErrorCode)));
                        }
                    }
                }

                return(Content("Error: Unknown error occurred."));
            }

            string idTokenOrError = FirebaseAuthHelper.SignInWithEmailAndPassword(email, password);
            string idToken;

            if (idTokenOrError.StartsWith("error: "))
            {
                JObject errorJObject = JObject.Parse(idTokenOrError.Remove(0, 7));
                return(Content(FirebaseAuthHelper.GenerateNiceErrorMessage(errorJObject["message"].ToString())));
            }
            else
            {
                idToken = idTokenOrError.Remove(0, 9);
            }

            using (DatabaseContext database = new DatabaseContext())
            {
                string username = Request.Form["username"];

                if (database.Users.Any(u => u.Username == username))
                {
                    FirebaseAuth.DefaultInstance.DeleteUserAsync(userRecord.Uid).Wait();
                    return(Content("There is another user with that username, and we don't allow duplicate usernames. Sorry!"));
                }

                User user = new User
                {
                    Username    = username,
                    FirebaseUid = userRecord.Uid
                };
                database.Users.Add(user);
                database.SaveChanges();
            }

            FirebaseAuthHelper.SendVerificationEmail(idToken);

            TimeSpan expirationTimeSpan;

            if (Request.Form["remember-me"] == "on")
            {
                expirationTimeSpan = TimeSpan.FromDays(14);
            }
            else
            {
                expirationTimeSpan = TimeSpan.FromDays(1);
            }

            SessionCookieOptions options = new SessionCookieOptions()
            {
                ExpiresIn = expirationTimeSpan
            };

            try
            {
                string sessionCookie = FirebaseAuth.DefaultInstance.CreateSessionCookieAsync(idToken, options).Result;

                CookieOptions cookieOptions = new CookieOptions()
                {
                    Expires  = DateTimeOffset.UtcNow.Add(options.ExpiresIn),
                    HttpOnly = true,
                    Secure   = EnvironmentHelper.KeepCookiesSecure()
                };

                Response.Cookies.Append("authSession", sessionCookie, cookieOptions);
                return(Content("success"));
            }
            catch (FirebaseAuthException)
            {
                return(Content("Error: Failed to create a session cookie."));
            }
        }