public void GetQrCodeImageAsDataUriThrowsOnInvalidSize() { var qr = new TestQrProvider(); var target = new TwoFactorAuth(qrcodeprovider: qr); target.GetQrCodeImageAsDataUri("Test", "VMR466AB62ZBOKHE", 0); }
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 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 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 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 GetQrCodeImageAsDataUriThrowsOnInvalidSize() { var qr = new TestQrProvider(); var target = new TwoFactorAuth(null, 6, 30, Algorithm.SHA1, qr); target.GetQrCodeImageAsDataUri("Test", "VMR466AB62ZBOKHE", 0); }
public void VerifyTotpUriIsCorrect() { var qr = new TestQrProvider(); var target = new TwoFactorAuth(issuer: "Test&Issuer", qrcodeprovider: qr); var data = DecodeDataUri(target.GetQrCodeImageAsDataUri("Test&Label", "VMR466AB62ZBOKHE")); Assert.AreEqual("test/test", data["mimetype"]); Assert.AreEqual("base64", data["encoding"]); Assert.AreEqual("otpauth://totp/Test%26Label?secret=VMR466AB62ZBOKHE&issuer=Test%26Issuer&period=30&algorithm=SHA1&digits=6@200", data["data"]); }
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; } }
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) }); }
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; } }
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; } }
public async Task <IActionResult> GetValidationToken() { var groupId = this.GroupId(); if (groupId.HasValue) { var group = (await this.groupRepository.GetById(groupId.Value)); var tfa = new TwoFactorAuth(group.Name); return(new JsonResult(new { name = group.Name, qrCode = tfa.GetQrCodeImageAsDataUri(group.Name, group.Secret) })); } return(new JsonResult("nope")); }
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 VerifyTotpUriIsCorrect() { var qr = new TestQrProvider(); var target = new TwoFactorAuth("Test&Issuer", 6, 30, Algorithm.SHA1, qr); var data = DecodeDataUri(target.GetQrCodeImageAsDataUri("Test&Label", "VMR466AB62ZBOKHE")); Assert.AreEqual("test/test", data["mimetype"]); Assert.AreEqual("base64", data["encoding"]); Assert.AreEqual("otpauth://totp/Test%26Label?secret=VMR466AB62ZBOKHE&issuer=Test%26Issuer&period=30&algorithm=SHA1&digits=6@200", data["data"]); }
public static string GenerateQrCode(string username, string secret) { return(tfa.GetQrCodeImageAsDataUri(username, secret, 256)); }
public void GetQrCodeImageAsDataUriThrowsOnInvalidSize() { var qr = new TestQrProvider(); var target = new TwoFactorAuth(null, 6, 30, Algorithm.SHA1, qr); target.GetQrCodeImageAsDataUri("Test", "VMR466AB62ZBOKHE", 0); }
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); } }