【发布时间】:2014-10-21 06:39:34
【问题描述】:
我有一个带有 Authorize 属性的控制器。如果用户未经授权,我预计不会创建控制器。但似乎确实如此。有什么方法可以改变这种行为并在不创建控件本身的情况下使 Authorize 生成 401 响应?
我为什么需要这个?我有一些面向管理员的控制器,它们仅针对经过身份验证的用户。它在基本控制器的构造函数中有一些逻辑。目前我必须检查用户是否为空,这似乎是一种浪费。
【问题讨论】:
标签: asp.net-mvc
我有一个带有 Authorize 属性的控制器。如果用户未经授权,我预计不会创建控制器。但似乎确实如此。有什么方法可以改变这种行为并在不创建控件本身的情况下使 Authorize 生成 401 响应?
我为什么需要这个?我有一些面向管理员的控制器,它们仅针对经过身份验证的用户。它在基本控制器的构造函数中有一些逻辑。目前我必须检查用户是否为空,这似乎是一种浪费。
【问题讨论】:
标签: asp.net-mvc
您可以从AuthorizeAttribute 派生并以您想要的方式处理它。该请求将首先访问这个被覆盖的方法,让您有机会决定是允许进一步处理请求还是拒绝它。您还可以通过添加 AllowAnonymous 属性来选择忽略特定方法(例如 Login),或者通过从 Attribute 类派生来定义您自己的属性。
一个工作示例如下:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class RdbiAuthorizationAttribute : AuthorizeAttribute
{
/// <summary>
/// Verifies that the logged in user is a valid organization user.
/// </summary>
/// <param name="filterContext"></param>
public override void OnAuthorization(AuthorizationContext filterContext)
{
Guard.ArgumentNotNull(filterContext, "filterContext");
Guard.ArgumentNotNull(filterContext.Controller, "filterContext.Controller");
bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(
typeof(AllowAnonymousAttribute), inherit: true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(
typeof(AllowAnonymousAttribute), inherit: true);
if (skipAuthorization)
{
return;
}
if (string.IsNullOrEmpty(filterContext.HttpContext.User.Identity.Name))
throw new AuthenticationException("User must be logged in to access this page.");
var controller = filterContext.Controller as BaseController;
if (controller != null)
{
var user = controller.GetUser();
if (user == null)
{
throw new InvalidOperationException(string.Format("Logged in user {0} is not a valid user", filterContext.HttpContext.User.Identity.Name));
}
}
base.OnAuthorization(filterContext);
}
}
【讨论】: