Когда я развертываю свой проект WebAPI на IIS-8 и тестирование использует Postman, оно выдает мне ошибку «Ошибка HTTP 401.2 - Несанкционированный
Вы не авторизованы для просмотра этой страницы из-за неправильных заголовков аутентификации.
Дополнительная информация:
Эта ошибка возникает, когда заголовок 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, я передал имя пользователя и пароль в разделе Basic Auth вместе с телом запроса Json.