Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would still use the built in ASP.NET forms authentication but just customize it to your needs.</p> <p>So you'll need to get your User class to implement the IPrincipal interface and then write your own custom cookie handling. Then you can simply just use the built in [Authorize] attribute.</p> <p>Currently I have something similar to the following...</p> <p>In my global.asax</p> <pre><code>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&lt;IWebUserRepository&gt;(); try { WebUser current = webUserRepository.GetById(webuserid); //Refresh the cookie var formsAuth = Kernel.Get&lt;IFormsAuthService&gt;(); 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; } } </code></pre> <p>AccountController.cs</p> <pre><code>[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); } </code></pre> <p>And finally my FormsAuthService:</p> <pre><code>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; } </code></pre> <p>HTHs<br> Charles</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload