服务器上的Web API身份验证

时间:2017-05-09 11:47:17

标签: asp.net-web-api

我正在编写一个与Web API通信的Windows应用程序。以下是我打电话的方式:

HttpClient client = null;
        HttpClientHandler handler = new HttpClientHandler() { PreAuthenticate = true, Credentials = CredentialCache.DefaultCredentials };
        client = new HttpClient();
        client.BaseAddress = new Uri(apiBaseAddress);
        var byteArray = Encoding.ASCII.GetBytes(Environment.UserName);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
        HttpResponseMessage response = client.GetAsync("api/Tickets/AuthenticateUser").Result;

我正在传递当前记录的凭据。我编写了一个连接到db的过滤器,检查用户名是否存在。代码:

public class BasicAuthenticationWindowsAppAttribute : System.Web.Http.Filters..AuthorizationFilterAttribute
{
    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (actionContext.Request.Headers.Authorization == null)
        {
            actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        }
        else
        {
            string authToken = actionContext.Request.Headers.Authorization.Parameter;
            string Handle = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
            GenericIdentity gi = new GenericIdentity(Handle);
            Thread.CurrentPrincipal = new GenericPrincipal(gi, null);
            HttpContext.Current.User = Thread.CurrentPrincipal;
            Amo_MasterDataEntities amoMasterDataContext = new Amo_MasterDataEntities();
            var query = from a in amoMasterDataContext.allassociatemasters
                        where a.Handle == Handle
                        select a;
            //If Handle is present in AMOMasterData.AllAssociatemaster table

            if (query.Count() > 0)
            {
                //TicketsController tc = new TicketsController();
                string assocId = "", fName ="", lName = "";
                bool authenticated = false;
                foreach (var item in query)
                {
                    assocId = item.AssociateID;
                    fName = item.FirstName;
                    lName = item.LastName;
                    authenticated = true;
                }
                AuthInfo info = new AuthInfo();
                info.AssociateId = assocId;
                info.FirstName = fName;
                info.LastName = lName;
                info.IsAuthenticated = authenticated;
                actionContext.Request.Properties.Add(new KeyValuePair<string, object>("AuthInfo", info));
                base.OnAuthorization(actionContext);

            }
            //else return error
            else
            actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);

        }
    }
}

当我在本地系统中运行Web服务时,它可以工作。但是当我在服务器上部署Web服务时,它给了我401 Unauhorized Message。

我在IIS中启用了基本身份验证和Windows身份验证,而Web.config包含<authentication mode="Windows" />

修改: 我能够从我部署的服务器访问Web API方法。 但是当我从另一台机器上的Windows客户端调用Web API时,它会抛出401错误。

我应该使用CORS吗?如果是,请告诉我怎么做?

任何人都可以为此提供解决方案。

1 个答案:

答案 0 :(得分:0)

我找到了原因,..

我没有将处理程序传递给HttpClient的构造函数,这是问题所在。所以在上面的代码替换:

client = new HttpClient();

with:

client = new HttpClient(handler);

这样一个愚蠢的错误。抱歉,麻烦。