I am trying to implement custom Forms authentication in an ASP.NET MVC 5 app, but I have not done this before and need some help. I am not using the membership provider, but have followed (parts of) http://tech.pro/tutorial/1216/implementing-custom-authentication-for-aspnet. So I am using a CustIdentity and CustPrincipal.
Here is Application_AuthenticateRequest from Global.asax.cs:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new CustIdentity(ticket);
var principal = new CustPrincipal(identity);
HttpContext.Current.User = principal;
}
}
It works fine this far, and I can call HttpContext.Current.User.IsInRole("Admin") successfully at the end of the above method.
However, when I try User.IsInRole("Admin") from a view, I get: 'You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class' Since I do not use the membership provider, WebSecurity.InitializeDatabaseConnection should not apply (I already have my SQL user table, etc. setup).
So I try
var user = User as CustPrincipal;
if (user != null && user.IsInRole("Admin"))
....
But User cannot be cast to CustPrincipal, so always returns null.
What am I missing here?