public async Task <IActionResult> GetQrCode(string UserName) { try { TwoFactorAuth TFAuth = new TwoFactorAuth(); string URL; string sKey = string.Empty; string sName = string.Empty; sKey = TFAuth.CreateSecret(160); sName = UserName; // dSetReq.Tables(0).Rows(0)("NAME"); sKey = TFAuth.CreateSecret(160); URL = TFAuth.GetQrCodeImageAsDataUri(sName, sKey); string value = URL + "" + sKey; return(Ok(new BizResponseClass { ReturnCode = enResponseCode.Success, ReturnMsg = value, })); } catch (Exception ex) { //return BadRequest(ex.ToString()); return(BadRequest(new BizResponseClass { ReturnCode = enResponseCode.InternalError, ReturnMsg = ex.ToString(), ErrorCode = enErrorCode.Status500InternalServerError })); } }
public void CreateSecretOverrideAllowInsecureDoesNotThrowOnSecureRNG() { var rng = new TestRNGProvider(true); var target = new TwoFactorAuth(null, 6, 30, Algorithm.SHA1, new TestQrProvider(), rng); var r = target.CreateSecret(); Assert.AreEqual("ABCDEFGHIJKLMNOP", target.CreateSecret()); }
public void CreateSecretOverrideAllowInsecureDoesNotThrowOnSecureRNG() { var rng = new TestRNGProvider(true); var target = new TwoFactorAuth(null, 6, 30, Algorithm.SHA1, new TestQrProvider(), rng); var r = target.CreateSecret(); Assert.AreEqual("ABCDEFGHIJKLMNOP", target.CreateSecret()); }
public void CreateSecretOverrideAllowInsecureDoesNotThrowOnSecureRNG() { var rng = new TestRNGProvider(true); var target = new TwoFactorAuth(rngprovider: rng); var r = target.CreateSecret(); Assert.AreEqual("ABCDEFGHIJKLMNOP", target.CreateSecret()); }
public void CreateSecretOverrideAllowInsecureDoesNotThrowOnInsecureRNG() { var rng = new TestRNGProvider(false); var target = new TwoFactorAuth(rngprovider: rng); var r = target.CreateSecret(80, CryptoSecureRequirement.AllowInsecure); Assert.AreEqual("ABCDEFGHIJKLMNOP", target.CreateSecret(80, CryptoSecureRequirement.AllowInsecure)); }
public void CreateSecretGeneratesDesiredAmountOfEntropy() { var rng = new TestRNGProvider(true); var target = new TwoFactorAuth(rngprovider: rng); Assert.AreEqual("A", target.CreateSecret(5)); Assert.AreEqual("AB", target.CreateSecret(6)); Assert.AreEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZ", target.CreateSecret(128)); Assert.AreEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", target.CreateSecret(160)); Assert.AreEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", target.CreateSecret(320)); Assert.AreEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVWXYZ234567A", target.CreateSecret(321)); }
public async Task <IActionResult> Create(string groupName) { if (!string.IsNullOrWhiteSpace(groupName)) { if (await this.groupRepository.GetByName(groupName) != null) { return(Ok("Helaas bestaat deze naam al")); } var tfa = new TwoFactorAuth(groupName); var group = new Group() { Name = groupName, Secret = tfa.CreateSecret(160) }; if (await this.groupRepository.Save(group) && group.GroupId.HasValue) { var jwt = JoinGroupJwtBased(group); group.RefreshToken = GenerateRefreshToken(); await this.groupRepository.Save(group); return(new JsonResult(new { name = group.Name, qrCode = tfa.GetQrCodeImageAsDataUri(group.Name, group.Secret), token = jwt, refreshToken = group.RefreshToken })); } } return(Ok("Er is geen naam ontvangen")); }
public void CreateSecretThrowsOnInsecureRNGProvider() { var rng = new TestRNGProvider(); var target = new TwoFactorAuth(rngprovider: rng); target.CreateSecret(); }
protected void Page_Load(object sender, EventArgs e) { Accounts useracc = null; using (VendingModelContainer dc = new VendingModelContainer()) { var useraccs = dc.Set <Accounts>(); useracc = useraccs.First(x => x.UserID == User.Identity.Name); } if (IsPostBack) { return; } if (useracc.TOTPSecret == "") { tfa = new TwoFactorAuth(WWWVars.SiteName); string secret = tfa.CreateSecret(160); totps.ImageUrl = tfa.GetQrCodeImageAsDataUri(User.Identity.Name, secret, 200); Session["totps"] = secret; twofasetupcompletebox.Visible = false; } else { twofasetupcompletebox.Visible = true; twofasetupbox.Visible = false; } }
public IActionResult setup2FA([FromHeader] string token) { // Check if the user managed to login with user and password but don't check 2fa here if (Logins.Verify(token, false, false) != null) { // Check if the user has 2fa enabled List <LoginSession> v = Program.db.Query <LoginSession>($"SELECT * FROM LoginSession WHERE id = '{token}';"); LoginSession u = v.Count > 0 ? v.First() : null; // Get the user that owns this session List <User> users = Program.db.Query <User>($"SELECT * FROM User WHERE id='{u.userId}';"); User user = users.Last(); if (user.twoFactorConfirmed) { return(BadRequest("2FA is already enabled for this account.")); } else { TwoFactorAuth tfa = new TwoFactorAuth("Cashier API", qrcodeprovider: new SkiaSharpQrCodeProvider()); //TODO: Change org to company name from global settings (WIP) string secret = tfa.CreateSecret(160); user.twoFactorSecret = secret; user.twoFactorConfirmed = false; Program.db.Update(user); return(Ok(tfa.GetQrCodeImageAsDataUri("Cashier API", secret))); } } else { return(Unauthorized()); } }
public void CreateSecretThrowsOnInsecureRNGProvider() { var rng = new TestRNGProvider(); var target = new TwoFactorAuth(null, 6, 30, Algorithm.SHA1, new TestQrProvider(), rng); target.CreateSecret(); }
public ActionResult Step1() { if (string.IsNullOrEmpty((string)Session["secret"])) { Session.Add("secret", tfa.CreateSecret()); } return(View(tfa)); }
public ActionResult Step1() { if (string.IsNullOrEmpty((string)Session["secret"])) { // Though the default is an 80 bits secret (for backwards compatibility reasons) we // recommend creating 160+ bits secrets (see RFC 4226 - Algorithm Requirements) Session.Add("secret", tfa.CreateSecret(160)); } return(View(tfa)); }
public IActionResult twoFa() { if (csgo.Controllers.adminController.tokenAccess.validateToken(Request, adminController.tokenType.twofactor)) { if (csgo.core.requestsHelper.processRequest(Request)) { return(Json(new { success = "false", message = "You are sending to many requests. Blacklist will expire in 30 seconds." })); } var userId = TempData["userId"]; if (userId == null) { TempData["toast"] = "{type:'error',message:'You are not authorized. An error occured try again later 2.'}"; return(this.Redirect(@Url.Action("index", "home"))); } if (TempData["mobile"] != null) { ViewBag.isMobile = true; } var token2FA = (string)TempData["token2FA"]; if (token2FA != null && token2FA.Length < 3) { Console.WriteLine("Need to setup authnetificator. curent token " + token2FA); TempData["userId"] = (int)userId; ViewBag.userId = (int)userId; string temp = ""; if (TempData["temp2FAToken"] != null) { temp = (string)TempData["temp2FAToken"]; } else { temp = tfa.CreateSecret(160); } ViewBag.temp2FAToken = temp; TempData["temp2FAToken"] = temp; TempData["toast"] = "{type:'warning',message:'You need to setup your 2FA Authentification to continue using this site.'}"; csgo.Controllers.adminController.tokenAccess.createToken(Request, adminController.tokenType.twofactor); return(View()); } TempData.Remove("temp2FAToken"); Console.WriteLine("Need to login with authnetificator. curent token " + token2FA); TempData["userId"] = (int)userId; TempData["token2FA"] = token2FA; csgo.Controllers.adminController.tokenAccess.createToken(Request, adminController.tokenType.twofactor); return(View()); } TempData["toast"] = "{type:'error',message:'You are not authorized. An error occured try again later 3.'}"; return(this.Redirect(@Url.Action("index", "home"))); }
private void wizardPage2_Initialize(object sender, AeroWizard.WizardPageInitEventArgs e) { if (!wizardPage2.AllowNext) { tfa = new TwoFactorAuth("Vending control system"); if (otpsecret == "") { otpsecret = tfa.CreateSecret(160); } var pic = Convert.FromBase64String(tfa.GetQrCodeImageAsDataUri(adminemailtextbox.Text, otpsecret, 150).Substring(22)); Image image = Image.FromStream(new MemoryStream(pic)); otpsecretpicture.Image = image; } }
private void Button1_Click(object sender, EventArgs e) { string FullName = textBox1.Text; if (FullName.Length != 0 && maskedTextBox1.TextLength != 0) { secret = tfa.CreateSecret(160); var uri = tfa.QrCodeProvider.GetQrCodeImage(String.Format("otpauth://totp/{0}?secret={1}&issuer=TFA Store", FullName, secret), 150); //Console.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(uri)); Image x = (Bitmap)((new ImageConverter()).ConvertFrom(uri)); pictureBox1.Image = x; RegiStrKey(FullName, secret); } }
private void newotpsecretbutton_Click(object sender, EventArgs e) { DialogResult tmpres = MessageBox.Show("Existing 2FA secret will be rewritten, you have to scan QR code again. Proceed?", "Warning!!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (tmpres == DialogResult.Yes) { tfa = new TwoFactorAuth("Vending control system"); otpsecret = tfa.CreateSecret(160); var pic = Convert.FromBase64String(tfa.GetQrCodeImageAsDataUri(adminemailtextbox.Text, otpsecret, 150).Substring(22)); Image image = Image.FromStream(new System.IO.MemoryStream(pic)); otpsecretpicture.Image = image; wizardPage2.AllowNext = false; checkotpbutton.Enabled = true; } }
private void newotpsecretbutton_Click(object sender, EventArgs e) { DialogResult tmpres = MessageBox.Show("Существующий секрет двухфакторной авторизации для администратора сайта будет перезаписан. Продолжить?", "Внимание!!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (tmpres == DialogResult.Yes) { tfa = new TwoFactorAuth("Vending control system"); otpsecret = tfa.CreateSecret(160); var pic = Convert.FromBase64String(tfa.GetQrCodeImageAsDataUri(adminemailtextbox.Text, otpsecret, 150).Substring(22)); Image image = Image.FromStream(new System.IO.MemoryStream(pic)); otpsecretpicture.Image = image; wizardPage2.AllowNext = false; checkotpbutton.Enabled = true; } }
public async Task ConnectUserAsyncWhenInvalidMfa() { var tfa = new TwoFactorAuth(); _session.Account.MfaSecret = tfa.CreateSecret(); await TestHelpers.Instance.AccountDao.TryInsertOrUpdateAsync(_session.Account); var result = await _controller.ConnectUserAsync(new ApiSession { Identity = _session.Account.Name, Mfa = tfa.GetCode(string.Concat(_session.Account.MfaSecret.Reverse())), }); Assert.AreEqual(JsonSerializer.Serialize(new BadRequestObjectResult(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.MFA_INCORRECT))), JsonSerializer.Serialize((BadRequestObjectResult)result)); }
public async Task<ActionResult> All() { var group = (await this.groupRepository.GetById(this.GroupId().Value)); var tfa = new TwoFactorAuth(group.Name); if (string.IsNullOrWhiteSpace(group.Secret)) { group.Secret = tfa.CreateSecret(160); await this.groupRepository.Save(group); } return base.Ok(new { QrToken = tfa.GetQrCodeImageAsDataUri("Maaltijdplanner", group.Secret) }); }
public void CreateSecretGeneratesDesiredAmountOfEntropy() { var rng = new TestRNGProvider(true); var target = new TwoFactorAuth(null, 6, 30, Algorithm.SHA1, new TestQrProvider(), rng); Assert.AreEqual("A", target.CreateSecret(5)); Assert.AreEqual("AB", target.CreateSecret(6)); Assert.AreEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZ", target.CreateSecret(128)); Assert.AreEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", target.CreateSecret(160)); Assert.AreEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", target.CreateSecret(320)); Assert.AreEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567ABCDEFGHIJKLMNOPQRSTUVWXYZ234567A", target.CreateSecret(321)); }
public async Task <ActionResult <ApiResponse <UserProperties> > > EnableMfa() { try { var userName = User?.Identity?.Name; var userId = User?.Claims.Where(x => x.Type == CustomClaims.USER_ID).FirstOrDefault()?.Value; if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(userId)) { return(BadRequest(RequestResponse.BadRequest("Something went wrong trying to validate your request."))); } string secret; var cacheKey = $"{MFA_CACHE_KEY}{userId}"; bool doesExists = memoryCache.TryGetValue(cacheKey, out secret); var currentProperties = await firebaseDbService.GetUserProperties(userId); if (currentProperties != null && currentProperties.IsMfaEnabled) { memoryCache.Remove(cacheKey); memoryCache.Set(cacheKey, currentProperties.Secret, cacheEntryOptions); currentProperties.Account = userName; currentProperties.Issuer = issuer; return(Ok(new ApiResponse <UserProperties>(currentProperties))); } if (!doesExists) { secret = twoFactorAuth.CreateSecret(160); memoryCache.Set(cacheKey, secret, cacheEntryOptions); var result = new UserProperties(userId, secret, issuer, userName); return(Ok(new ApiResponse <UserProperties>(result))); } var cacheResult = new UserProperties(userId, secret, issuer, userName); return(Ok(new ApiResponse <UserProperties>(cacheResult))); } catch (Exception) { return(BadRequest(RequestResponse.BadRequest("Something went wrong trying to enable Mfa."))); } }
static void Main(string[] args) { // inicializa le autenticador multifactor, el argumento es // el nombre de la aplicación que se muestra, por ejmeplo «Facebook» // en este caso es «Aplicación Tal» var tfa = new TwoFactorAuth(ConfigurationManager.AppSettings["appname"]); // pregunta quién es el usaurio Console.WriteLine("teclee su identificación de usaurio"); var _userInput = Console.ReadLine(); // localiza el usuario en la base de datos var _user = Users.FindUser(_userInput); // si el usuario no existe no existe se crea y se genera el código Qr if (_user == null) { Console.WriteLine($"tu eres nuevo por aquí, cual es tu nombre completo"); var _realname = Console.ReadLine(); // crea un nuevo usuario _user = new UserModel { UserName = _userInput, RealName = _realname }; // genera el secreto y almacenalo junto con el usuario _user.Secret = tfa.CreateSecret(160); // el html contiene el qrcode generado en un <img> // toma como argumento el realname que pondremos en la tag y el secre del usuario var _html = $"<p>{_user.RealName} ({_user.UserName})</p>"; _html += $"<p><img src=\"{tfa.GetQrCodeImageAsDataUri(_user.RealName,_user.Secret)}\" ></p>"; _html += $"<p>{_user.Secret}</p>"; // escribe un html con el QrCode en una imagen File.WriteAllText(QrCodeFile, _html); Console.WriteLine($"escanea el código qr en file:///{QrCodeFile}"); // guarda el usuario Users.AddUser(_user); } else { Console.WriteLine($"verificando credenciales de acceso para «{_user.RealName}»"); } if (_user.LastLogin != null) { Console.WriteLine($"el último acceso fue {_user.LastLogin.ToString()}"); } else { Console.WriteLine("no se han registrado accesos al sistema"); } // toma el código que escriba en el usuario Console.WriteLine("teclee el código que se muestra en la app de autenticación"); var _code = Console.ReadLine(); // verifica que código dado Console.WriteLine($"verificando «{_code}»"); if (tfa.VerifyCode(_user.Secret, _code)) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("correcto! acceso consedido"); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("nop... eso no pinchó, te vas pal carajo"); } // refresca el last login del usuario _user.LastLogin = DateTime.Now; Users.UpdateUser(_user); // el resto sale invisible Console.ForegroundColor = Console.BackgroundColor; // elimina el html si existe if (File.Exists(QrCodeFile)) { File.Delete(QrCodeFile); } }
public async Task <IActionResult> EnableAuthenticator() { try { var user = await GetCurrentUserAsync(); //// Update Status string oldvalue = JsonConvert.SerializeObject(user); //user.TwoFactorEnabled = true; //await _userManager.UpdateAsync(user); //// Update Status //return Ok(new TwoFactorAuthResponse { ReturnCode = enResponseCode.Success, ReturnMsg = EnResponseMessage.EnableTroFactor }); var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await _userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); } string Newvalue = JsonConvert.SerializeObject(user); UserChangeLogViewModel userChangeLogViewModel = new UserChangeLogViewModel(); userChangeLogViewModel.Id = user.Id; userChangeLogViewModel.Newvalue = Newvalue; userChangeLogViewModel.Type = EnuserChangeLog.TwofactoreChange.ToString(); userChangeLogViewModel.Oldvalue = oldvalue; long userlog = _iuserChangeLog.AddPassword(userChangeLogViewModel); TwoFactorAuth TFAuth = new TwoFactorAuth(); //string URL; string sKey = string.Empty; // string sName = string.Empty; //sKey = TFAuth.CreateSecret(160); // sName = user.UserName; // dSetReq.Tables(0).Rows(0)("NAME"); sKey = TFAuth.CreateSecret(160); //URL = TFAuth.GetQrCodeImageAsDataUri(sName, sKey); // string value = URL + "" + sKey; // string code123 = TFAuth.GetQrCodeImageAsDataUri(, string secret) user.PhoneNumber = sKey; var result = await _userManager.UpdateAsync(user); if (result.Succeeded) { var model = new EnableAuthenticatorViewModel { SharedKey = FormatKey(sKey), //AuthenticatorUri = GenerateQrCodeUri(user.UserName, unformattedKey) // UserName = user.UserName, AuthenticatorUri = TFAuth.GetQrCodeImageAsDataUri(user.UserName, sKey) }; return(Ok(new EnableAuthenticationResponse { ReturnCode = enResponseCode.Success, ReturnMsg = EnResponseMessage.TwoFactorActiveRequest, EnableAuthenticatorViewModel = model })); } return(BadRequest(new EnableAuthenticationResponse { ReturnCode = enResponseCode.Fail, ReturnMsg = EnResponseMessage.TwoFactorActiveRequest, ErrorCode = enErrorCode.NotFound })); //if (string.IsNullOrEmpty(user.Email)) //// This Condition by pankaj for when user login with molile the email field is null so. //{ // var model = new EnableAuthenticatorViewModel // { // SharedKey = FormatKey(unformattedKey), // AuthenticatorUri = GenerateQrCodeUri(user.UserName, unformattedKey) // }; // return Ok(new EnableAuthenticationResponse { ReturnCode = enResponseCode.Success, ReturnMsg = EnResponseMessage.TwoFactorActiveRequest, EnableAuthenticatorViewModel = model }); //} //else //{ // var model = new EnableAuthenticatorViewModel // { // SharedKey = FormatKey(unformattedKey), // AuthenticatorUri = GenerateQrCodeUri(user.Email, unformattedKey) // }; // return Ok(new EnableAuthenticationResponse { ReturnCode = enResponseCode.Success, ReturnMsg = EnResponseMessage.TwoFactorActiveRequest, EnableAuthenticatorViewModel = model }); //} } catch (Exception ex) { _logger.LogError(ex, "Date: " + _basePage.UTC_To_IST() + ",\nMethodName:" + System.Reflection.MethodBase.GetCurrentMethod().Name + "\nControllername=" + this.GetType().Name, LogLevel.Error); return(BadRequest(new TwoFactorAuthResponse { ReturnCode = enResponseCode.InternalError, ReturnMsg = ex.ToString(), ErrorCode = enErrorCode.Status500InternalServerError })); } }
public void CreateSecretThrowsOnInsecureRNGProvider() { var rng = new TestRNGProvider(); var target = new TwoFactorAuth(null, 6, 30, Algorithm.SHA1, new TestQrProvider(), rng); target.CreateSecret(); }
public static string CreateSecret() { return(tfa.CreateSecret(512, CryptoSecureRequirement.RequireSecure)); }