First time I use ASP.NET Identity and I probably miss something.
I know how to use ApplicationUserManager (my class extending UserManager) but I want to create a method inside of it that use UserManager methods because I don't want to repeat code.
Calling "base" doesn't work.
EDIT: the "base" didn't work because I had the method as static (I don't know why I wrote that).
Now it doesn't give me errors but if I try to call it from my Web API Controller I get the "Does not contain a definition of ..." error.
ApplicationUserManager:
namespace BLL
{
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
public async Task<int> RegistraPuntoScan(string userId, string sitoVisitato)
{
var user = await base.FindByIdAsync(userId);
if(user != null)
{
var s = new Stringa(sitoVisitato);
if (!user.URLVisitati.Contains(s))
{
user.Punti++;
user.URLVisitati.Add(s);
await base.UpdateAsync(user);
return 1;
}
else
{
return 2;
}
}
else
{
return 3;
}
}
}
}
Web API Controller:
namespace MyProject.Controllers.API
{
[CustomAuthorization]
public class PuntiController : ApiController
{
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
[HttpPost]
public IHttpActionResult RegistraPuntoScan(RegisterPointScanVm vm)
{
ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
var idUtente = ClaimsPrincipal.Current.Identity.GetUserId();
var user = UserManager.FindById(idUtente);
switch(UserManager.RegistraPuntoScan(idUtente, vm.ScannedURL))
{
case 1:
return Ok();
case 2:
return Conflict();
case 3:
return BadRequest();
}
return BadRequest();
}
}
}
I solved the problem.
I was unable to call the new method because I have the ApplicationUserManager in another project and I probably forgot to delete the default ApplicationUserManager n IdentityConfig.cs, or VisualStudio created it, I don't know.
I deleted IdentityConfig (I have all the classes in other projects) and referenced the right one, now everything works.
Related
I want to authorize user in WebApi using ClaimsIdentity. In my AccountController which inherits ApiController class I have my two methods to test user authentication. One is a proper method used to receive user's data from other app based on his AD name and authenticates him saving his data as a Claim. The other one is a test method which I call after the previous one to check if the user is authenticated and has claims set.
Unfortunately the login method doesn't seem to set his Identity correctly even though the cookie is generated. The second method than works as if the user wasn't even authenticated and doesn't have any claims.
I have tried some various combination of creating his Identity but nothing seems to work.
Maybe you can see what I am missing.
AccountController.cs
[HttpGet]
[Route("account/login/{userActDirName}/{realmId}")]
public async Task<IHttpActionResult> Login(string userActDirName, long realmId)
{
//getting user data
var user = await UserManager.FindAsync(userActDirName, "1");
if (user == null)
{
user = new ApplicationUser() { UserName = userActDirName };
IdentityResult result = await UserManager.CreateAsync(user, "1");
if (!result.Succeeded)
{
...
}
user = await UserManager.FindAsync(userActDirName, "1");
}
Authentication.SignOut();
ClaimsIdentity cookieIdentity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
cookieIdentity.AddClaim(new Claim(ClaimTypes.Name, userActDirName));
cookieIdentity.AddClaim(new Claim("User", JsonConvert.SerializeObject(userData)));
Authentication.SignIn(new AuthenticationProperties() { IsPersistent = false }, cookieIdentity);
}
private ApplicationUserManager _userManager;
private IAuthenticationManager Authentication
{
get { return HttpContext.Current.GetOwinContext().Authentication; }
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
IdentityConfig.cs
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = false
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = -1,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
Startup.cs
[assembly: OwinStartup(typeof(Api.Startup))]
namespace Api
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
}
Since you used the string "User" while creating claim for complete user object as JSON, using the following code :
cookieIdentity.AddClaim(new Claim("User", JsonConvert.SerializeObject(userData)));
Therefore when checking if the user is authenticated or not, use the follwoing code to check if the above mentioned claim exists or not. It will also give you full JSON that you stored while adding "User" Claim.
Remember the type casting below is very important
also use the following namespace
using System.Security.Claims;
before using the following code
var user = "";
var claims =
((ClaimsIdentity)filterContext.RequestContext.Principal.Identity).Claims;
foreach (var c in claims)
{
if (c.Type == "User")
user = c.Value;
}
I have used this code in a custom "AuthorizationFilterAttribute". Therefore I have
filterContext object
you can get
RequestContext object
easily in any WebAPI-Method e.g.
this.RequestContext.Principal.Identity
therefore,
var claims =
((ClaimsIdentity)this.RequestContext.Principal.Identity).Claims;
will work in any web api controller.
I have reviewed several answers to this on StackOverflow, and I have applied and compared with no answer to my particular case. Here is what I have up to this point:
*****In Web.Config*****
<add name="DefaultConnection" connectionString="Data Source=LAPTOP-2UA8GL6L\SQLEXPRESS;Initial Catalog=FHSF_DEV;Integrated Security=True" providerName="System.Data.SqlClient" />
in IdentityModels.cs
public class ApplicationUser : IdentityUser
{
public DateTime BirthDate { get; set; }
public string City { get; set; }
public string State { get; set; }
public int UserDetailID { get; set; }
public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
{
return Task.FromResult(GenerateUserIdentity(manager));
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
In IdentityConfig.cs
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
return Task.FromResult(0);
}
}
public class SmsService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
}
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
}
//////// Commented out the rest of the code within this class //////
public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore(context.Get()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
//manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
//{
// MessageFormat = "Your security code is {0}"
//});
//manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
//{
// Subject = "Security Code",
// BodyFormat = "Your security code is {0}"
//});
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = false;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
And, in the calling program where the error takes place
if (IsValid)
{
// Validate the user's email address
//var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
//ApplicationUser user = manager.FindByName(Email.Text);
/////////////////////////////////////////////////////////////////
//var userStore = new UserStore<IdentityUser>();
//var userManager = new UserManager<IdentityUser>(userStore);
//IdentityUser user = userManager.FindByEmail(Email.Text);
var provider = new DpapiDataProtectionProvider("FHSFReset");
ApplicationDbContext context = ApplicationDbContext.Create();
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());
///////////////////////////////////////////////////////////
// The error occurs below /////////////////////////////////
///////////////////////////////////////////////////////////
ApplicationUser user = userManager.FindByEmail(Email.Text);
///////////////////////////////////////////////////////////
// Error msg: System.InvalidOperationException: 'The entity
// type ApplicationUser is not part of the model for the
// current context.'
///////////////////////////////////////////////////////////
if (user == null)
{
FailureText.Text = "The user either does not exist or is not confirmed.";
ErrorMessage.Visible = true;
return;
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
// Send email with the code and the redirect to reset password page
userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(
provider.Create("EmailRestPW"));
NOTE: I am utilizing Identity, Entity Framework (I think) and OWIN. I am attempting to keep the Authorization/Authentication tables within my database and the tables are there. I (as is shown above) have added customized fields in AspNetUsers and should be reflected in the connectivity.
Is there anything apparent that indicates I have set this up incorrectly such that the error is occurring?
I am using asp.net identity 2.2.1 and I want to delete a user when he/she tries to hit a specific action method in one of none account controllers. Being into many SO question each of them points to a version dependent solution and frankly I couldn't find a to the point answer.
Why there is no plain and simple documentation on deleting an identity user and most importantly why this feature is not part of the identity it self?
Please note that I am using individual user accounts for external logins no local login is allowed.
My identity.cofig files looks like below:
namespace SocialManager
{
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
return Task.FromResult(0);
}
}
public class SmsService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
}
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = false
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
}
UserManager has method that looks like this:
public virtual async Task<IdentityResult> DeleteAsync(TUser user)
Use it to delete user record.
Update:
here is how to delete a user:
// id is id of the user to be deleted.
var user = await userManager.FindByIdAsync(id); //use async find
var result = await userManager.DeleteAsync(user);
if (result.Succeeded)
{
// user is deleted
}
I have been digging into asp.net identity for few days now , and I'm trying to extend and customize the Identity
I created a custom class out of everything and it's working so far
which means I Extended all identity classes:
public class User : IdentityUser<string, UserLogin, UserRole, UserClaim>, IUser, IUser<string>
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
you can see that all classes in the User class are my classes,
I did that for UserStore, RoleStore, UserManager , RoleManager:
public class HEUserManager : UserManager<User>
{
public HEUserManager(IUserStore<User> store)
: base(store)
{
}
public static HEUserManager Create(IdentityFactoryOptions<HEUserManager> options, IOwinContext context)
{
var manager = new HEUserManager(new HEUserStore(context.Get<HEDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<User>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<User>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<User>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<User>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
// Configure the application sign-in manager which is used in this application.
public class HESignInManager : SignInManager<User, string>
{
public HESignInManager(HEUserManager userManager, IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(User user)
{
return user.GenerateUserIdentityAsync((HEUserManager)UserManager);
}
public static HESignInManager Create(IdentityFactoryOptions<HESignInManager> options, IOwinContext context)
{
return new HESignInManager(context.GetUserManager<HEUserManager>(), context.Authentication);
}
}
public class HEUserStore : UserStore<User, Role, string, UserLogin, UserRole, UserClaim>, IUserStore<User>, IUserStore<User,string>, IDisposable
{
public HEUserStore(DbContext context) : base(context)
{
}
}
public class HERoleManager : RoleManager<Role, string>
{
public HERoleManager(IRoleStore<Role, string> store) : base(store)
{
}
}
public class HERoleStore : RoleStore<Role, string, UserRole>
{
public HERoleStore(DbContext context) : base(context)
{
}
}
it's working so far, but before customizing this , crating a user using the user manager is very straight forward , and created a user for me in the database
but now I have to put the user id manually every time , otherwise I'm getting this error
An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in mscorlib.dll but was not handled in user code
Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
is this normal or did i do something wrong? if it's normal , how can I generate the IDs automatically again?
I have a new application built on top of the the Identity 2.0 Samples and am having trouble with UsersAdmin/Edit. When the the application posts back to this page the line var result = UserManager,AddToRolesAsync(string userid, string[] roles) generates a result error stating that the email address is already taken. "The Email somename#somedomain.com is already taken." With result.Succeeded = false; Here is the HttpPost Controller
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(EditUserViewModel editUser,
params string[] selectedRole)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByIdAsync(editUser.Id);
if (user == null)
{
return HttpNotFound();
}
// if email is unchanged don't update it.
if (user.Email != editUser.Email)
{
user.Email = editUser.Email;
user.EmailConfirmed = false;
}
var userRoles = await UserManager.GetRolesAsync(user.Id);
selectedRole = selectedRole ?? new string[] { };
// Identity tries to update the email address here and returns an error?
var result = await UserManager.AddToRolesAsync(user.Id,
selectedRole.Except(userRoles).ToArray<string>());
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View(new EditUserViewModel()
{
Id = user.Id,
MemberName = user.Name,
Email = user.Email,
MemberAddress = user.Address,
RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
{
Selected = userRoles.Contains(x.Name),
Text = x.Name,
Value = x.Name
})
});
}
result = await UserManager.RemoveFromRolesAsync(user.Id, userRoles.Except(selectedRole).ToArray<string>());
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
}
return RedirectToAction("Index");
}
ModelState.AddModelError("", "Something failed.");
return View(editUser);
}
Here is the UserManager class (Vanilla from the Samples):
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
I can see that the ApplicationUserManager Create Method in IdentityConfig is firing and that is where 'RequireUniqueEmail = true;' is set, but I do not understand why it is trying to create a new User and not just validating the existing user that UserManager.FindByIdAsync(editUser.Id) returns above. Here is the ApplicationUserManager class:
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationIdentityDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
// why is this being enforced on an existing user when the email
// address is not being updated but UserRoles are?
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug in here.
manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is: {0}"
});
manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser>
{
Subject = "SecurityCode",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
As you can see I haven't gotten as far as configuring the Two Factor Authentication. Any insight you can provide would be most helpful. Thanks in Advance.