自定义WebAPI身份验证-如何对HttpContext进行身份验证.现在的要求LogoUserIdentity.姓名



我有一个webapi,它将在公司网络上运行,并且只有经过windows身份验证的用户。

我正在尝试验证HttpContext。现在的要求LogoUserIdentity。直接命名,因为HttpContext。现在的要求LogoUserIdentity。IsAuthenticated返回false。

我这样做是为了避免非管理员用户的用户登录弹出窗口。

using System;
using System.Diagnostics;
using System.Web.Http;
using System.Web;
using System.Web.Http.Controllers;
namespace myAPI.Helpers
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AuthorizeCustomAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
// HttpContext.Current.User.Identity.Name is always empty at this point
// and must authenticate first with HandleUnauthorizedRequest(actionContext)
// but that pops up an annoying login screen,
// HttpContext.Current.Request.LogonUserIdentity.Name has the value I need
// but it is not authenticated which raises some security concerns
// Check against a list of admins
if (HttpContext.Current.Request.LogonUserIdentity.IsAuthenticated && Authentication.IsAdmin( HttpContext.Current.Request.LogonUserIdentity.Name ))
{
Debug.WriteLine("USER IS AUTHORIZED");
}
else
{
Debug.WriteLine("USER IS DENIED");
//HandleUnauthorizedRequest(actionContext); // This will popup a login unless it is overridden
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK); // return a blank response instead
}
}
}
}

这是我最简单的解决方案:

  • 仅检查已知管理员的身份验证
  • 重定向未通过身份验证的管理员
  • 非管理员不会得到登录弹出窗口
using System;
using System.Diagnostics;
using System.Web.Http;
using System.Web;
using System.Web.Http.Controllers;
namespace myAPI.Helpers
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AuthorizeCustomAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
// Check against a list of admins
if (Authentication.IsAdmin(HttpContext.Current.User.Identity.Name) || Authentication.IsAdmin( HttpContext.Current.Request.LogonUserIdentity.Name ))
{
if(HttpContext.Current.User.Identity.IsAuthenticated || HttpContext.Current.Request.LogonUserIdentity.IsAuthenticated )
{
Debug.WriteLine("USER IS AUTHORIZED");
} else
{
Debug.WriteLine("USER IS AN ADMIN BUT IS UNAUTHENTICATED");
HandleUnauthorizedRequest(actionContext); // redirect to get authenticated
}
}
else
{
Debug.WriteLine("USER IS NOT AN ADMIN AND IS DENIED");
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK); // return a blank response
}
}
}
}

相关内容

最新更新