Authorize users at the controller level from web.Config

In my controller annotation [Authorized].

I would like to get a list of authorized users that are configured in my web.config file.

<add key="authorizedUsers" value="jeff,dan,mindy,claudia"/>

I know that in the controller you can do something like:

[Authorize Users="jeff,dan,mindy,claudia"]

But I would rather just update the web.config file without recompiling. Do I need to read the web.config file for my list and then add it to the attribute [Authorize]? I also use Windows authentication for this, and not for authentication.

+4
source share
2 answers

You can implement a custom attribute, AuthorizeAttribute, which inherits from AuthorizeAttribute.

, FormAuthentication. .

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CustomUserAuthorizeAttribute : AuthorizeAttribute
{
    private string[] _usersSplit
    {
        get
        {
            var authorizedUsers = ConfigurationManager.AppSettings["authorizedUsers"];

            return authorizedUsers.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
        }
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException("httpContext");
        IPrincipal user = httpContext.User;
        return user.Identity.IsAuthenticated && (_usersSplit.Length <= 0 || Enumerable.Contains(_usersSplit, user.Identity.Name, StringComparer.OrdinalIgnoreCase));
    }
}

[CustomUserAuthorize]
public ActionResult Test()
{
    ViewBag.Message = "Your page.";

    return View();
}

FYI: . . .

+7

. , web.config.

<system.web>
  <authorization>
    <allow roles="admin"/>
  </authorization>
</system.web>

:

<authorization>
    <allow users="?"/>
    <deny users="*"/>
</authorization>

-

0

All Articles