Asp.net web api 服务器上的Web API身份验证

Asp.net web api 服务器上的Web API身份验证,asp.net-web-api,Asp.net Web Api,我正在编写一个Windows应用程序,它将与Web API进行通信。以下是我打电话的方式: HttpClient client = null; HttpClientHandler handler = new HttpClientHandler() { PreAuthenticate = true, Credentials = CredentialCache.DefaultCredentials }; client = new HttpClient();

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

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;
我正在传递当前记录的凭据。我已经编写了一个过滤器,它连接到数据库并检查用户名是否存在。守则:

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);

        }
    }
}
公共类基本身份验证WindowsAppAttribute:System.Web.Http.Filters..AuthorizationFilterAttribute
{
授权时的公共覆盖无效(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if(actionContext.Request.Headers.Authorization==null)
{
actionContext.Response=new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
其他的
{
字符串authToken=actionContext.Request.Headers.Authorization.Parameter;
字符串句柄=Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
GenericEntity gi=新的GenericEntity(句柄);
Thread.CurrentPrincipal=新的GenericPrincipal(gi,null);
HttpContext.Current.User=Thread.CurrentPrincipal;
Amo_MasterDataEntities Amo MasterDataContext=新Amo_MasterDataEntities();
var query=来自amoMasterDataContext.allassociatemasters中的
其中a.Handle==句柄
选择一个;
//如果AMOMasterData.AllAssociatemaster表中存在句柄
if(query.Count()>0)
{
//TicketController tc=新的TicketController();
字符串assocId=“”,fName=“”,lName=“”;
bool=false;
foreach(查询中的var项)
{
assocId=item.AssociateID;
fName=item.FirstName;
lName=item.LastName;
已验证=真;
}
AuthInfo info=新的AuthInfo();
info.AssociateId=assocId;
info.FirstName=fName;
info.LastName=lName;
info.IsAuthenticated=已验证;
actionContext.Request.Properties.Add(新的KeyValuePair(“AuthInfo”,info));
基于授权(actionContext);
}
//else返回错误
其他的
actionContext.Response=new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
}
}
当我在本地系统中运行web服务时,它可以工作。但当我在服务器上部署web服务时,它会给我401条未经授权的消息

我已在IIS和Web.config中启用了基本身份验证和Windows身份验证。配置包含

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

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

谁能给我一个解决办法。

我找到了原因

我没有将处理程序传递给HttpClient的构造函数,这就是问题所在。因此,在上述代码中,请替换:

client = new HttpClient();
与:

client = new HttpClient(handler);
这样愚蠢的错误。很抱歉给您添麻烦。

我找到了原因

我没有将处理程序传递给HttpClient的构造函数,这就是问题所在。因此,在上述代码中,请替换:

client = new HttpClient();
与:

client = new HttpClient(handler);

这样愚蠢的错误。很抱歉给您添麻烦。

如果您取出
?Hi Mark,它会工作吗。我尝试过删除,但仍然获得了401。您是否尝试在您的
OnAuthorization
方法中加入任何类型的日志记录?没有标记。我没有设置任何日志记录。我使用HttpClient的方式是正确的。因为在网上的一些帖子中,我看到HttpClient可能无法正确发送AuthorizationHeader之类的东西。那么,您将如何解决您的问题呢?洛威尔:如果你拿出
?Hi Mark,它能用吗。我尝试过删除,但仍然获得了401。您是否尝试在您的
OnAuthorization
方法中加入任何类型的日志记录?没有标记。我没有设置任何日志记录。我使用HttpClient的方式是正确的。因为在网上的一些帖子中,我看到HttpClient可能无法正确发送AuthorizationHeader之类的东西。那么,您将如何解决您的问题呢?英雄联盟