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.
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));
}
}
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With