Organizational Research By

Surprising Reserch Topic

httpcontext current user httpcontext user using -'asp.net,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,forms-authentication'


httpcontext current user httpcontext user  using -'asp.net,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,forms-authentication'

Is HttpContext.Current.User in global asax not the same as HttpContext.User in an action method?  I assigned the user some roles, but they seem to get lost.

The code below shows what is happening.  Both Asserts get hit when a user is logged on, first in global asax, then the action method.  However they give different results.

First this:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    // ... omitted some code to check user is authenticated
    FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

    string[] roles = new string[] { "admin", "user" };

    HttpContext.Current.User =
        new System.Security.Principal.GenericPrincipal(identity, roles);

    Assert(HttpContext.User.IsInRole("admin"));
}


Then this in my action method:

public ActionResult Index()
{
    bool isAdmin = HttpContext.User.IsInRole("admin");

    Assert(isAdmin); // this fails, isAdmin is false

    // ...
}


I used the following resources

This SO answer

http://csharpdotnetfreak.blogspot.com/2009/02/formsauthentication-ticket-roles-aspnet.html
    
asked Sep 7, 2015 by rajesh
0 votes
29 views



Related Hot Questions



Government Jobs Opening


...