【发布时间】:2019-11-01 17:12:15
【问题描述】:
我有一个 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
}
}
}
}
【问题讨论】:
标签: c# asp.net-web-api windows-authentication asp.net-authorization