我已经在我的AuthorizeAttribute中实现了一个自定义WebAPI (请注意,这与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);
}
}发布于 2015-03-31 18:17:09
我想知道下面这段代码:
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);在某个地方,您必须使用如下所示来配置您自己的层:
var cookieAuthenticationOptions = new CookieAuthenticationOptions
{
LoginPath = new PathString(loginPath)
}
app.UseCookieAuthentication(cookieAuthenticationOptions);当您从身份验证过滤器返回401时,OWIN基础结构将自动将您重定向到您指定的任何LoginPath。但是当试图满足这个请求时,它正在调用您的过滤器,但是由于用户没有被授权,它返回一个401,这会导致重定向到LoginPath,等等。
因为这是一个API调用,所以您需要以不同的方式处理401。下面的博客文章介绍了这种情况。
http://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/
简而言之,在配置CookieAuthenticationOptions时,您需要指定自己的Provider,并且只有当它不是AJAX请求时才直接进行。
var cookieAuthenticationOptions = new CookieAuthenticationOptions
{
LoginPath = new PathString(loginPath),
Provider = new CookieAuthenticationProvider()
{
OnApplyRedirect = context =>
{
if (!context.Request.IsAjaxRequest())
{ context.Response.Redirect(context.RedirectUri); }
}
}
}发布于 2015-04-01 11:15:02
您可以尝试删除OnAuthorization并添加以下内容:
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var owinContext = HttpContext.Current.GetOwinContext();
var authenticated = owinContext.Authentication.User.Identity.IsAuthenticated;
return authenticated & SecurityHelper.IsUserAuthorized();
}我不明白为什么您要重定向失败的身份验证,当然API应该只返回401吗?
https://stackoverflow.com/questions/29375333
复制相似问题