通过捕获客户端的服务帐户名来进行Web API授权 [英] Web api authorization by capturing client's service account name

查看:85
本文介绍了通过捕获客户端的服务帐户名来进行Web API授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部,我在执行某个Web api控制器操作中的授权时遇到问题.这是一个.net Framework 4.6.1应用程序,一个MVC 5应用程序对该Web api进行了调用.我们在客户端(MVC5)和Web API上都实现Windows身份验证.客户端和服务器都使用相同的服务帐户(运行应用程序池的帐户名),并且这些帐户位于单独的服务器上.

All, I am having an issue with implementing authorization on one of my web api controller action. This is a .net framework 4.6.1 app and an MVC 5 application makes calls into this web api. We implement windows authentication both on the client(MVC5) and web api. Both client and server use the same service account(The account name the app pool runs under) and these are on separate servers.

使用AD帐户对客户端应用程序的用户进行身份验证,然后才能进入对Web api进行调用的MVC应用程序部分.

Users of the client app is authenticated using AD account before they get to the MVC app section that makes calls to the web api.

我在api控制器操作中添加了[Authorize]属性,但该请求返回的状态为401未经授权.

I added the [Authorize] attribute to the api controller action, but the request is returned with 401 unauthorized status.

因此,我添加了一个自定义授权逻辑,该逻辑将来自客户端应用的传入用户名(服务帐户)与api的配置文件(在每种环境中)中配置的内容进行比较,然后接受/拒绝请求.请参见下面的代码)在actionContext.RequestContext.Principal.Identity.Name行上是一个空字符串.

So I added a custom authorization logic, that compares the incoming user name(service account) from the client app, against whats configured in the api's config file(in each environment) and accept/deny request.But the User (please see code below) on the line actionContext.RequestContext.Principal.Identity.Name is an empty string.

我尝试在IIS上的MVC5应用程序配置上启用asp.net模拟,但还是没有运气

I tried enabling asp.net impersonation on the MVC5 apps configuration on IIS, but still no luck

有人做过类似的事情吗?

Has anyone done something similar?

自定义授权逻辑

public class CustomAuthorize : AuthorizeAttribute
{

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var isAuthorized = false;
        var environment = ConfigurationManager.AppSettings["Env"];
        var configuredAccountName = ConfigurationManager.AppSettings["appserviceaccountname"];
        string incomingServiceAccountName = null;

        try
        {

            if(actionContext.RequestContext.Principal != null && actionContext.RequestContext.Principal.Identity != null)
            {

                incomingServiceAccountName = actionContext.RequestContext.Principal.Identity.Name;
                if(!string.IsNullOrWhiteSpace(incomingServiceAccountName))
                {
                    logger.Error(string.Format("Service account name passed in is : {0}", incomingServiceAccountName));
                    switch (environment)
                    {
                        case "Dev":
                            if(incomingServiceAccountName.ToLower().Equals(configuredAccountName.ToLower()))
                            {
                                isAuthorized = true;
                            }
                            break;

                        default:
                            break;
                    }
                }

            }
            else if(actionContext.RequestContext.Principal == null)
            {
                logger.Error("Principal is null");
            }
            else
            {
                logger.Error("Identity is null");
            }

        }
        catch (Exception ex)
        {
            logger.Error(string.Format("Error occurred while authorizing the user inside the class CustomAuthorize and method IsAuthorized with {0}", ex.Message));
            isAuthorized = false;
        }

        return isAuthorized;

    }
}

进行api调用的MVC5客户端代码

MVC5 Client code that makes the api call

using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://webapiurl");
                var jsonString = new StringContent(JsonConvert.SerializeObject(search), Encoding.UTF8, "application/json");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.PostAsync(client.BaseAddress, jsonString).Result;
                if (response.IsSuccessStatusCode)
                {
                    var result = response.Content.ReadAsStringAsync().Result;
                    mydate = JsonConvert.DeserializeObject<List<mydate>>(result);
                }
            }
    }

推荐答案

您是否已在服务器上的IIS中设置Windows身份验证?IIS Windows Auth提供程序也必须存在(协商,NTLM),以允许IIS尝试通过AD进行身份验证.

Have you set Windows Auth in IIS on on the server? IIS Windows Auth providers also must be present (Negotiate, NTLM) to allow IIS to try to authenticate with AD.

这篇关于通过捕获客户端的服务帐户名来进行Web API授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆