My Startup.Auth.cs如下
[assembly: OwinStartup(typeof(IoTWeb.App_Start.Startup))]
namespace IoTWeb.App_Start
{
public class Startup
{
private const int DEFAULTTIMEOUT = 5;
private const int DEFAULTEXPIRETIMESPAN = 5;
public void Configuration(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
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
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity =
SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(TimeSpan.FromMinutes(DEFAULTTIMEOUT),
(manager, user) => Task.FromResult(manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie)))
},
SlidingExpiration = true,
ExpireTimeSpan = TimeSpan.FromMinutes(DEFAULTEXPIRETIMESPAN)
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
}
和我的UserStoreService.cs
public class UserStoreService : IUserStore<User>, IUserPasswordStore<User>, IUserEmailStore<User>
{
private readonly TenantEntities context = new TenantEntities();
public Task<User> Find(string userName, string password)
{
Task<User> task = context.User.Where(
apu => apu.UserName == userName && apu.Password == password)
.FirstOrDefaultAsync();
return task;
}
我的帐户控制器
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var manager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
User user = manager.Find(model.UserName, model.Password);
if (user != null)
{
IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
return RedirectToLocal(returnUrl);
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "Login failed due to incorrect credentials.");
return View(model);
}
[AllowAnonymous]
public ActionResult Register()
{
// Remove the Cookie in Here as he goes a bit further
if (ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("FinancesModelDataCookie"))
{
HttpCookie cookie = ControllerContext.HttpContext.Request.Cookies["FinancesModelDataCookie"];
if (cookie != null)
{
cookie.Expires = DateTime.Now.AddDays(-1);
ControllerContext.HttpContext.Response.Cookies.Add(cookie);
}
}
return View();
}
注册成功,但登录卡在
User user = manager.Find(model.UserName, model.Password);
并提供以下异常
这里编辑的是Identity.Config
public class ApplicationUserManager : UserManager<User>
{
public ApplicationUserManager()
: base(new UserStoreService())
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context)
{
var manager = new ApplicationUserManager();
manager.PasswordHasher = new PasswordHasher(); // new NoPasswordHasher();
// 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,
};
manager.PasswordValidator = new CustomPasswordValidator(6); //commented for and used above defined validator
//manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<User>
//{
// Subject = "SecurityCode",
// BodyFormat = "Your security code is: {0}"
//});
manager.EmailService = new EmailService();
IDataProtectionProvider dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<User>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}