Search code examples
c#asp.netasp.net-mvcweb-configwindows-authentication

ASP.NET MVC How to get allowed users? in windows authentication


I have web config:

<location allowOverride="true" path="Admin/Secure">
    <system.web>
      <authorization>
        <allow users="SpecificUserName1" />
        <allow users="SpecificUserName2" />
        <deny users="*" />
      </authorization>
    </system.web>
  </location>

I need to get all users (SpecificUserName1, SpecificUserName2) in runtime. How can i accomplish this?

UPDATE I need to do this in View

Now i use default approach:

@if (Request.IsAuthenticated)
{
 //secure menu
}

Now: Menu showing for all users in domain, but access granted only users which exists in web.config

Need: Hide menu/allow access for all users in domain except users which exists in web.config

UPDATE

I found the solution http://forums.asp.net/t/1787320.aspx/1

UrlAuthorizationModule.CheckUrlAccessForPrincipal(Request.Url.AbsolutePath, HttpContext.Current.User, HttpContext.Current.Request.HttpMethod);

Solution

  • First things first, don't use web.config to control authorization in an ASP.NET MVC application.

    Use the [Authorize] attribute. Decorate the corresponding controller/action with it:

    [Authorize(Users = "SpecificUserName1, SpecificUserName2")]
    public ActionResult Secure()
    {
        ...
    }
    

    You could then externalize those usernames in a constant and reuse the value. By the way depending on where exactly you need those values, there might be other ways to retrieve them.