我正在尝试扩展默认的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 属性为 false 的操作中,即使在 BypassValidation 属性中使用的 Debug 窗口中显示如下:
set:26833123 True set:39602703 True get:43424763 False get:43424763 False get:43424763 False // 这应该是“True”的调用...
我注意到了两件事:
- TypeId(属性的唯一标识符)在具有 BypassValidation = true 和具有 BypassValidation = false 的调用之间不同。
- id“ 43424763”没有相应的设置
有什么想法吗?
谢谢,Joao