I've read a lot of questions and answers on this topic, but none of them have helped me solve this issue.
The problem I'm having is that the HttpContext.Current.User
or just User
property is of type RolePrincipal
instead of my custom principal.
This is an MVC 5 web app using Windows Authentication (intranet only application). My custom principal is a subclass of WindowsPrincipal
and I did implement my own RoleProvider
for use in Authorize attribute tags.
When I attempt to use the principal by casting it to my custom principal from IPrincipal
on the current HttpContext I get an error stating that it's of type RolePrincipal, which obviously cannot be casted to my custom principal. I am setting my custom principal in the Application_PostAuthenticationRequest
event:
protected void Application_PostAuthenticationRequest(object sender, EventArgs e)
{
if (User == null)
return;
using(EntityContext db = new EntityContext ())
{
var user = db.Users.SingleOrDefault(u => u.ADName.Equals(User.Identity.Name));
HttpContext.Current.User = new PcsPrincipal((WindowsIdentity)User.Identity, user);
}
}
When I put a breakpoint in that method it appears to never get called, which may explain why it's not getting set to my custom principal.
I've reviewed the following QAs, but they have not been able to resolve the issue:
- using custom IPrincipal and IIdentity in MVC3 - Added the registration of the event handler in Global.asax.cs's Init method. Didn't seem to make a difference. Also the
_application
variable appeared to be invalid in MVC5. - RoleProvider dosn't work with custom IIdentity and IPrincipal on server - Made the changes in the web.config file, but this caused various errors during runtime with errors saying that the ASP.NET pipeline is configured incorrectly.
What am I doing incorrectly to not have the Principal set? Let me know if more code needs to be posted.
EDIT: Setting the HttpContext.Current.User to my custom principal in the WindowsAuthentication.OnAuthenticate event does not resolve this issue. The exact same behavior is exhibited using that method.