Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorize Users at Controller level from web.Config

Tags:

asp.net-mvc

In my controller the [Authorized] annotation.

I'd like to go get a list of authorized users that are setup in my web.config file.

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

I know in the controller you can do something like:

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

But I'd rather just update the web.config file without having to re-compile. Is there anyway to do read the web.config file for my list and then add it to the [Authorize] attribute? I'm also using Windows Authenticationfor this rather than Form Authentication.

like image 747
webdad3 Avatar asked Mar 22 '23 06:03

webdad3


1 Answers

You can implement custom AuthorizeAttribute which inherits from AuthorizeAttribute.

I assume you are using FormAuthentication. Otherwise, it won't work.

[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));
    }
}

Usage

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

    return View();
}

FYI: Ideally, you want to use role based authentication, and store them in database. It is a little bit easy to maintain. However, it is up to your need.

like image 142
Win Avatar answered Mar 31 '23 14:03

Win