根据应用程序设置自定义授权属性

时间:2017-02-07 12:55:58

标签: c# configuration authorize-attribute

上下文:C#ASP.NET MVC Web应用程序。

我添加了一些功能,可以让我模仿其他用户。 我应该只在应用程序配置时看到此功能。所以我在web.config中添加了appSettings。

<add key="AllowImpersonation" value="true" />

(不)显示控件很简单。但我也想禁用相应的控制器方法。

我首先想到的是自定义AuthorizeAttribute,我可以在其中检查配置设置。

更好的是更通用的属性,您可以在其中提供要检查的(布尔)Appsetting的键。像这样:

namespace MILF.Security
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class ConfigSetting_Authorize : AuthorizeAttribute
    {
        private string _configKey;

        public ConfigSetting_Authorize(string configKey)
        {
            if (string.IsNullOrEmpty(configKey))
                throw new ArgumentException("configKey");
            this._configKey = configKey;
        }

        //Core authentication, called before each action
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            try         
            {   
                return Convert.ToBoolean(AppSettingsHelper.Get<bool>(this._configKey))
            }
            catch (Exception)
            {
                return false;
            }
        }

        //Called when access is denied
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            SecurityLogManager securityLogManager = new SecurityLogManager(filterContext);
            var message = string.format("{0} triez to access shit that waz disabled.", filterContext.HttpContext.User.Identity.Name);
            securityLogManager.Write(message);
            securityLogManager = null;
        }
    }
}

namespace MILF.Utils
{
    public static class AppSettingsHelper
    {
        public static T Get<T>(string key)
        {
            var appSetting = ConfigurationManager.AppSettings[key];
            if (string.IsNullOrWhiteSpace(appSetting)) throw new Exception(key);

            var converter = TypeDescriptor.GetConverter(typeof(T));
            return (T)(converter.ConvertFromInvariantString(appSetting));
        }
    }
}

然后像这样使用它:

public class ImpersonateController : BaseController
{
    // GET: Impersonate
    [ConfigSetting_Authorize("AllowImpersonation")]
    public ActionResult Index()
    {
        if (!LoggedInUser.IsAdministrator)
        {
            return RedirectToAction("Index", "Home");
        }

        return View(new List<KBEAccounts.Account>());
    }   

    [ConfigSetting_Authorize("AllowImpersonation")]
    public ActionResult Impersonate(string Id)
    {
        if (!LoggedInUser.IsAdministrator)
        {
            return RedirectToAction("Index", "Home");
        }

        // Set the account to impersonate
        var service = new ActiveDirectoryUsersService();

        this.LoggedInUser =
            service.GetUserByLoginNameToImpersonate(
                Id,
                (string.IsNullOrWhiteSpace(LoggedInUser.ImpersonatorPersonnelId)) ?
                    LoggedInUser.EmployeeNumber :
                    LoggedInUser.ImpersonatorPersonnelId,
                (string.IsNullOrWhiteSpace(LoggedInUser.ImpersonatorCommonName)) ?
                    LoggedInUser.CommonName :
                    LoggedInUser.ImpersonatorCommonName,
                (string.IsNullOrWhiteSpace(LoggedInUser.ImpersonatorFullName)) ?
                    LoggedInUser.FullName :
                    LoggedInUser.ImpersonatorFullName);

        // redirect to home
        return RedirectToAction("", "");
    }       

}

但感觉我正在重新发明轮子。 enter image description here

.NET框架是否还没有提供此功能?

0 个答案:

没有答案