Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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? Help would be much appreciated!

share|improve this question

1 Answer 1

I got this working by commenting out this section from the web.config:

<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
    <providers>
      <clear />
      <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
    </providers>
</roleManager>-->

It appears my CustPrincipal was getting overwritten by the SimpleRoleProvider. I got this solution from this post: RoleProvider dosn't work with custom IIdentity and IPrincipal on server

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.