26629

Allowing both email and username for authentication

I'm creating two projects (MVC 5 and Web API) using ASP.Net Identity 2.1 and I couldn't find how to use both email and username for authentication (an area called Admin must use a username and the common area must use email addresses for authentication).

The problem is that there is only one method for authentication and it does not allow you to specify if you will compare with the email address or the username.

SignInHelper.PasswordSignIn

What should I do to achieve this?

Answer1:

SignInManager will not you help with it, you'll need to use UserManager and a bit more jiggery-pokery (that's technical term!):

This is what I have for this scenario:

var unauthUserByUsername = await userManager.FindByNameAsync(command.UserName); var unauthUserByEmail = await userManager.FindByEmailAsync(command.UserName); var unauthenticatedUser = unauthUserByUsername ?? unauthUserByEmail; if (unauthenticatedUser == null) { logger.Warn("User {0} is trying to login but username is not correct", command.UserName); return View(); // stop processing } var loggedInUser = await userManager.FindAsync(unauthenticatedUser.UserName, command.Password); if (loggedInUser == null) { // username is correct, but password is not correct logger.Warn("User {0} is trying to login with incorrect password", command.UserName); await userManager.AccessFailedAsync(unauthenticatedUser.Id); return View(); // stop processing } // Ok, from now on we have user who provided correct username and password. // and because correct username/password was given, we reset count for incorrect logins. await userManager.ResetAccessFailedCountAsync(loggedInUser.Id); if (!loggedInUser.EmailConfirmed) { logger.Warn("User {0} is trying to login, entering correct login details, but email is not confirmed yet.", command.UserName); return View("Please confirm your email"); // stop processing } if (await userManager.IsLockedOutAsync(loggedInUser.Id)) { // when user is locked, but provide correct credentials, show them the lockout message logger.Warn("User {0} is locked out and trying to login", command.UserName); return View("Your account is locked"); } logger.Info("User {0} is logged in", loggedInUser.UserName); // actually sign-in. var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; await userManager.SignInAsync(authenticationManager, loggedInUser, false);

This checks if user has confirmed email, if user is locked out and does lock user out after a certain number of attempts (given all other settings for locking-out are enabled).

Answer2:

This way both are allowed

var userEmail = await UserManager.FindByEmailAsync(model.Login); if (userEmail == null) { var user = await UserManager.FindByNameAsync(model.Login); if (user == null) { model.Login = ""; } } else { model.Login = userEmail.UserName; } var result = await SignInManager.PasswordSignInAsync(model.Login, model.Password, model.RememberMe, shouldLockout: false);

Recommend

  • How to move zeros to the end of a list [closed]
  • Finding the function caller in C
  • What the templating service ID?
  • ApplicationUserManager's Generate ___ Token methods
  • .net core get GetUserManager from ApplicationUser out of constructor
  • How to register ApplicationUserManager with IdentityServer DI framework?
  • Facebook Open Graph Story Custom Actions Keep Getting Rejected - Advice Please?
  • MySQL Query Tuning - Why is using a value from a variable so much slower than using a literal?
  • Display Current Video in Windows Phone 8 using AudioVideoCaptureDevice?
  • C# foreach - Is collection computed with each iteration? [duplicate]
  • Get Users in Group from Azure AD via Microsoft Graph
  • Add custom field for WooCommerce CSV Export plugin - For customer first order [closed]
  • Visual Basic 6 on Win7 64bit: Will developed program run on 32-bit Win OS?
  • concatenating select menus into a single form input
  • Laravel include causes error: Method Illuminate\\View\\View::__toString() must not throw an exce
  • Unity registration fails after iisreset
  • How Does Navigation in xamarin.forms Works?
  • HALF_PTR Windows data type
  • Implementation of RTTI using typeid
  • Spring security - same page to deliver different content based on user role
  • WARNING:root:Some characters could not be decoded, and were replaced with REPLACEMENT CHARACTER. Wit
  • Save image as is in photo album using swift
  • MVC - @Html.CheckBoxFor
  • Flask not finding files in my package's 'static' directory
  • Authentication failed with Azure Active Directory in Windows Phone
  • How to access meteor package name inside package?
  • How Get arguments value using inline assembly in C without Glibc?
  • Who propagate bugfixes across branches (corporate development)?
  • ThreadStatic in asynchronous ASP.NET Web API
  • Debugging VB6 Code From Visual Studio 2010
  • Allowing both email and username for authentication
  • Handling un-mapped Rest path
  • Get one-time binding to work for ng-if
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • How do you troubleshoot character encoding problems?
  • How to delete a row from a dynamic generate table using jquery?
  • using HTMLImports.whenReady not working in chrome
  • Authorize attributes not working in MVC 4
  • EntityFramework adding new object to nested object collection
  • Django query for large number of relationships