繁体   English   中英

从Postman测试时出现错误:HTTP错误401.2 - 未经授权

[英]I am getting error when testing from Postman : HTTP Error 401.2 - Unauthorized

当我在IIS-8上部署我的WebAPI项目并且测试使用Postman时,它给出了错误“HTTP错误401.2 - 未经授权由于无效的身份验证标头,您无权查看此页面。

更多信息:当服务器配置不支持发送到Web服务器的WWW-Authenticate标头时,会发生此错误。 检查资源的身份验证方法,并验证客户端使用的身份验证方法。 验证方法不同时会发生错误。 要确定客户端使用的身份验证类型,请检查客户端的身份验证设置。“

在当地它工作正常。

我的Web.Config内容是:

<configuration>
  <appSettings>
    <add key="WhiteListedIPAddresses"  value="::1,192.168.9.175,192.168.9.234"/> <!-- Example "::1,192.168.9.234" -->
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
    <customErrors mode="Off"/>

  <!--<authentication mode="Windows" /> -->

    </system.web>
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>

  </system.webServer>
  <connectionStrings>
  <!--<add name="myConnectionString" connectionString="Provider=ASAProv.80; Trusted_Connection=True;Data Source=softwrench;Persist Security Info=True;commlinks=TCPIP;" /> -->
  <add name="myConnectionString" connectionString="Provider=ASAProv.80; Trusted_Connection=True;Data Source=Corporate;Persist Security Info=True;commlinks=TCPIP;" />
</connectionStrings>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

基本认证码:



namespace WebApiSampleProject
{
    public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //------------------------------------------------------------------------------------------------------------------------------
            string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
            string sql;

            OleDbConnection conn;
            OleDbDataReader rdr;
            OleDbCommand cmd;
            //------------------------------------------------------------------------------------------------------------------------------

            var authHeader = actionContext.Request.Headers.Authorization;

            if (authHeader != null)
            {
                var authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
                var decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
                var usernamePasswordArray = decodedAuthenticationToken.Split(':');
                var userName = usernamePasswordArray[0];
                var password = usernamePasswordArray[1];


                //------------------------------------------------------------------------------------------------------------------------------
                conn = new OleDbConnection(connStr);
                conn.Open();

                sql = "SELECT ucode, upassword FROM user_list where ucode = ?";
                cmd = new OleDbCommand(sql, conn);
                OleDbParameter usercode = cmd.Parameters.Add("?", OleDbType.VarChar, 15);
                usercode.Value = userName;

                cmd.CommandType = CommandType.Text;
                rdr = cmd.ExecuteReader();

                var userid = "";
                var passcode = ""; 

                if (rdr.HasRows)
                {
                    while (rdr.Read())
                    {                             

                        userid = rdr["ucode"].ToString();

                        passcode = rdr["upassword"].ToString();
                    }
                }
                else
                {
                    Console.WriteLine("No rows found.");
                }


                rdr.Close();
                conn.Close();

                var isValid = userName == userid && password == passcode;

                //------------------------------------------------------------------------------------------------------------------------------

                if (isValid)
                {
                    var principal = new GenericPrincipal(new GenericIdentity(userName), null);
                    Thread.CurrentPrincipal = principal;

                    //actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK,"User " + userName + " successfully authenticated");

                    return;
                }
            }

            HandleUnathorized(actionContext);
        }

        private static void HandleUnathorized(HttpActionContext actionContext)
        {
            //var host = actionContext.Request.RequestUri.DnsSafeHost;
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Username or Password is Incorrect" );

            actionContext.Response.Headers.Add("WWW-Authenticate", "Basic Scheme='Data' location = 'http://192.168.9.234:");

        }



    }
}

在Webapiconfig中注册的基本身份验证为:

config.Filters.Add(new BasicAuthenticationAttribute());

使用Postman客户端我在基本身份验证下传递了用户名和密码以及Json请求体。

我已经设定

<section name="authorization" overrideModeDefault="Deny" /> 

<section name="authorization" overrideModeDefault="Allow" />

在applicationHost.Config文件中,修复问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM