我在我的 WebAPI 中实现了一个自定义 AuthorizeAttribute(请注意,这与 MVC AuthorizeAttribute 不同)。
我已经覆盖了 OnAuthorization 方法。在这种方法中,我检查用户是否经过身份验证。如果未通过身份验证,我会挑战用户登录。
我的自定义逻辑的一部分是检查经过身份验证的用户是否有权继续(基本上我检查他们的姓名/电子邮件。如果它存在于预定义的列表中,那么他们有权访问)。
我看到的问题是这样的:在用户成功验证但未能获得授权后,我看到有一个无限循环重定向到登录页面。
同样,用户凭据的挑战在于 OnAuthorization 方法。什么可能导致这种无限循环,一旦确定用户没有授权,如何防止这种情况发生?
* 用片段更新 *
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnAuthorization(actionContext); // Should this be here?
var owinContext = HttpContext.Current.GetOwinContext();
var authenticated = owinContext.Authentication.User.Identity.IsAuthenticated;
var request = System.Web.HttpContext.Current.Request;
if (!authenticated)
{
// Challenge user for crednetials
if (!request.IsAuthenticated)
{
// This is where the user is requested to login.
owinContext.Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
WsFederationAuthenticationDefaults.AuthenticationType);
}
}
else
{
// At this point the user ia authenticated.
// Now lets check if user is authorized for this application.
var isAuthorized = SecurityHelper.IsUserAuthorized();
if (isAuthorized)
{
// authorized.
return;
}
// not authorized.
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
}