Пользовательская аутентификация WebAPI - Как аутентифицировать HttpContext.Current.Request.LogonUserIdentity.Name - PullRequest
0 голосов
/ 01 ноября 2019

У меня есть 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
            }

        }
    }
}

1 Ответ

0 голосов
/ 01 ноября 2019

Это было мое самое простое решение:

  • Проверять только аутентификацию известных администраторов
  • Перенаправлять администраторов, которые не аутентифицированы
  • Не администраторы не получатлогин всплывающее окно
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
            }

        }
    }
}

...