public async Task <IActionResult> VerifyTOTPCode(TOTPRequest request)
        {
            User user = _dbContext.Users.SingleOrDefault(u => u.Id == request.RequestorId);

            if (user is null)
            {
                return(NotFound("User does not exist."));
            }

            byte[] totpSecret = Base32Encoding.ToBytes(user.TOTPSecret);
            Totp   totp       = new Totp(totpSecret);

            VerificationWindow window = new VerificationWindow(previous: 1, future: 1);
            bool isValid = totp.VerifyTotp(request.Code, out var _, window);

            if (isValid)
            {
                MFAToken token = await MFAToken.GenerateAsync(user.AccountId, user.TOTPSecret);

                return(Ok(token));
            }
            else
            {
                return(BadRequest("Code is invalid."));
            }
        }
Exemple #2
0
        public static void SaveTwoFactorAuthenticationToken(CMSDataContext db, HttpResponseBase response)
        {
            const string name = "_mfa";

            var expirationDays = db.Setting("TwoFactorAuthExpirationDays", "30").ToInt();
            var expires        = DateTime.Now.AddDays(expirationDays);
            var key            = string.Join("", "123".Select(c => Guid.NewGuid().ToString("N")));
            var token          = new MFAToken {
                Expires = expires,
                Key     = key,
                UserId  = Util.UserId
            };

            db.MFATokens.InsertOnSubmit(token);
            db.SubmitChanges();

            var cookie = new HttpCookie(name, token.Key)
            {
                Expires = expires, HttpOnly = true, Secure = !Util.IsDebug()
            };

            if (!cookie.Secure) // https://stackoverflow.com/questions/26627886/not-able-to-set-cookie-from-action
            {
                cookie.Domain = null;
            }
            response.AppendCookie(cookie);
        }
        public async Task <IActionResult> ValidateMFAToken(MFAToken token)
        {
            Guid identity = token.Identity;
            User user     = _dbContext.Users.SingleOrDefault(u => u.AccountId == identity);

            if (user is null)
            {
                return(NotFound());
            }

            await token.ValidateAsync(user.TOTPSecret);

            return(Ok(token));
        }