我正在尝试扩展他的默认Web Api授权属性,以允许经过身份验证的用户访问一组操作,即使它们未在应用程序中注册(例如,他们没有角色)。
public class AuthorizeVerifiedUsersAttribute : AuthorizeAttribute
{
/// <summary>
/// Gets or sets the authorized roles.
/// </summary>
public new string Roles { get { return base.Roles; } set { base.Roles = value; } }
/// <summary>
/// Gets or sets the authorized users.
/// </summary>
public new string Users { get { return base.Users; } set { base.Users = value; } }
private bool _bypassValidation;
/// <summary>
/// Gets of sets a controller or an action as an authorization exception
/// </summary>
public virtual bool BypassValidation
{
get
{
Debug.WriteLine("get:" + TypeId.GetHashCode() + " " + _bypassValidation);
return _bypassValidation;
}
set
{
Debug.WriteLine("set:" + TypeId.GetHashCode() + " " + value);
_bypassValidation = value;
}
}
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (BypassValidation)
{
return true;
}
else
{
//return false if user is unverified
}
}
return base.IsAuthorized(actionContext);
}
}
它正在被这样使用:
[AuthorizeVerifiedUsers]
public class UserProfileController : ApiController
{
[AuthorizeVerifiedUsers(BypassValidation = true)]
public bool Verify(string verificationCode)
{}
}
到目前为止,此操作是使用BypassValidation = true的唯一操作。
出现此问题是因为即使“调试”窗口(在BypassValidation属性中使用)显示以下内容,操作的BypassValidation属性为false:
设置:26833123正确 设置:39602703是的 得到:43424763错 得到:43424763错 get:43424763错误//调用应该有“True”......
我注意到两件事:
有什么想法吗?
提前致谢, 若昂
答案 0 :(得分:9)
Web API的工作方式是为父作用域调用authorize属性,在本例中为控制器,并且覆盖(动作的authorize属性)需要完成手动(如果我错了,请纠正我。)
因此,解决方案可能如下所示:
public class AuthorizeVerifiedUsersAttribute : AuthorizeAttribute
{
(...)
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
//retrieve controller action's authorization attributes
var authorizeAttributes = actionContext.ActionDescriptor.GetCustomAttributes<AuthorizeVerifiedUsersAttribute>();
//check controller and action BypassValidation value
if (BypassValidation ||
actionAttributes.Count > 0 && actionAttributes.Any(x => x.BypassValidation))
{
return true;
}
else
{
//return false if user is unverified
}
return base.IsAuthorized(actionContext);
}
}
答案 1 :(得分:3)
有点太晚了,但对于有类似问题的其他用户:在Web API 2中,您可以使用“OverrideAuthorization”覆盖所有先前的授权属性(全局授权过滤器,控制器授权属性等),然后只使用Authorize属性,没有指定角色。 Authorize属性的默认行为只是检查用户是否经过身份验证。
在这种情况下:
[YourCustomAuthorize]
public class UserProfileController : ApiController
{
[OverrideAuthorization]
[Authorize]
public bool Verify(string verificationCode)
{
// TODO
}
}