I have written a code that adds a user to my database using _userManager.CreateAsync
,here is my controller code:
public async Task<IActionResult> Create([FromForm] UserDetailsViewModel userview)
{
if (ModelState.IsValid)
{
SiteUser user = new SiteUser();
_mapper.Map(userview, user);//properties mapped using automapper.(works fine)
if (!userview.LockoutEnabled)
{
user.ExpirationTime = DateTime.MaxValue;//some custom property I added to my class
}
var result = await _userManager.CreateAsync(user,userview.Password);//user.LockoutEnabled is **false** here.
if (result.Succeeded)//user.LockoutEnabled is **true** here and also in database.
{
return new StatusCodeResult(StatusCodes.Status201Created);
}
else
{
return new StatusCodeResult(StatusCodes.Status400BadRequest);
}
}
else
{
return new StatusCodeResult(StatusCodes.Status400BadRequest);
}
}
This piece of code works fine and creates a user successfully. However, when the user is created the LockoutEnabled
field is equal to 1 in my database. which is not what I want. I have set a breakpoint just before CreateAsync(user,userview.Password)
and the user has it's lockout property set to false. Is there a default behavior that I need to change or am I missing something?
You can disable it when configuring security settings for your application:
In my case, in ConfigureServices
method in Startup.cs
- take a look at marked line:
var identityOptions = new Action<IdentityOptions>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.Password.RequireDigit = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.Password.RequiredLength = 3;
// lockout setup
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(2);
options.Lockout.MaxFailedAccessAttempts = 2;
options.Lockout.AllowedForNewUsers = true; // <<-- This line controls it
});
services.AddDefaultIdentity<ApplicationUser>(identityOptions);
// Rest of identity configuration...
Set options.Lockout.AllowedForNewUsers
to false
and it should do the trick.