上下文: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("", "");
}
}
.NET框架是否还没有提供此功能?