When I register a user using the following code:
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
return View(model);
}
}
I am able to access all of the views with the [Authorize] attribute. However, if I log out and back in with the same user I get an error page with
"InvalidOperationException: UserId not found"
The error seems to be coming from my SignInAsync function at the statement:
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
I am not adding a UserID and there is no UserId field in the user classs (its Id) or in the AspNetUsers table. The user exists in that table, but again, there is no UserId.
I have tried clearing the cookies etc, but still no luck in re-logging in. Am I doing the register wrong? I don't understand why the authentication is looking for the UserId field when it doesn't seem to exist
EDIT: When I login the first time...i get the error page. However, when I reopen the page and it reads the cookie, I have access to everything. What the heck is going on with the initial login?
here is the SignInAsync method:
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var _identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, _identity);
}
inclusion:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> 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;
}
}