我仍然会使用内置的ASP.NET窗体身份验证,但只是根据您的需要对其进行自定义。
因此,您需要让您的用户类实现IPrincipal接口,然后编写自己的自定义cookie处理。然后您只需使用内置的[authorize]属性即可。
目前我有类似以下的东西…
在my global.asax中
protected void Application_AuthenticateRequest()
{
HttpCookie cookie = Request.Cookies.Get(FormsAuthentication.FormsCookieName);
if (cookie == null)
return;
bool isPersistent;
int webuserid = GetUserId(cookie, out isPersistent);
//Lets see if the user exists
var webUserRepository = Kernel.Get<IWebUserRepository>();
try
{
WebUser current = webUserRepository.GetById(webuserid);
//Refresh the cookie
var formsAuth = Kernel.Get<IFormsAuthService>();
Response.Cookies.Add(formsAuth.GetAuthCookie(current, isPersistent));
Context.User = current;
}
catch (Exception ex)
{
//TODO: Logging
RemoveAuthCookieAndRedirectToDefaultPage();
}
}
private int GetUserId(HttpCookie cookie, out bool isPersistent)
{
try
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
isPersistent = ticket.IsPersistent;
return int.Parse(ticket.UserData);
}
catch (Exception ex)
{
//TODO: Logging
RemoveAuthCookieAndRedirectToDefaultPage();
isPersistent = false;
return -1;
}
}
会计总监.cs
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(LogOnForm logOnForm)
{
try
{
if (ModelState.IsValid)
{
WebUser user = AccountService.GetWebUserFromLogOnForm(logOnForm);
Response.Cookies.Add(FormsAuth.GetAuthCookie(user, logOnForm.RememberMe));
return Redirect(logOnForm.ReturnUrl);
}
}
catch (ServiceLayerException ex)
{
ex.BindToModelState(ModelState);
}
catch
{
ModelState.AddModelError("*", "There was server error trying to log on, try again. If your problem persists, please contact us.");
}
return View("LogOn", logOnForm);
}
最后,我的表单服务:
public HttpCookie GetAuthCookie(WebUser webUser, bool createPersistentCookie)
{
var ticket = new FormsAuthenticationTicket(1,
webUser.Email,
DateTime.Now,
DateTime.Now.AddMonths(1),
createPersistentCookie,
webUser.Id.ToString());
string cookieValue = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
{
Path = "/"
};
if (createPersistentCookie)
authCookie.Expires = ticket.Expiration;
return authCookie;
}
高温高压
查尔斯