我有一个可以在公司网络中使用的webapi,并且仅具有经过Windows身份验证的用户。
我试图直接验证HttpContext.Current.Request.LogonUserIdentity.Name,因为HttpContext.Current.Request.LogonUserIdentity.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
}
}
}
}
答案 0 :(得分:0)
这是我最简单的解决方案:
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
}
}
}
}