具有基本身份验证的应用程序可在本地主机上运行,​​但在 IIS 上发布后获得未经授权的用户

application with basic authentication works on local host but get unauthorized user after publish on IIS

我有一个用 MVC 4 web API 编写的遗留网站 API,它有基本的身份验证,当我测试它时,它在使用 POSTMAN 的本地主机上工作,当我在 iis 上发布时我得到401 - 未经授权:由于 credentials.i 无效,访问被拒绝已在 iis 服务器上为此 API 启用了基本身份验证,但我仍然遇到相同的错误,我应该在 iis 上还是在我的代码中更改某些内容?

Web Api 配置:

   config.Filters.Add(new BasicAuthenticationAttribute());
   // config.Filters.Add(new AuthorizeAttribute());      
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );


    // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
    // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
    // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
    //config.EnableQuerySupport();

    // To disable tracing in your application, please comment out or remove the following line of code
    // For more information, refer to: http://www.asp.net/web-api

    config.EnableSystemDiagnosticsTracing()

身份验证class:

     public class BasicAuthenticationAttribute: AuthorizationFilterAttribute
    {
   public override void OnAuthorization(HttpActionContext actionContext)
    {
 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];

    // Replace this with your own system of security / means of validating credentials
    var isValid = userName == "rene" && password == "2019";

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

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

        base.OnAuthorization(actionContext); 
    }
    else
    {
        HandleUnathorized(actionContext); 
    }
 }

我在部署到 IIS 时遇到过类似的问题,很难确定问题的主要原因。我建议检查应用程序是否抛出错误,这可能是导致错误的原因。

您可以尝试以下方法:

  • 确保所有依赖项都存在并在 IIS 上进行了配置 服务器。(.Net framework 3.5 .Net framework 4.5 等)
  • 错误或身份验证失败的事件查看器。
  • Windowslog/Application(如果退出则显示错误)。
  • Windowslog/Security 失败的身份验证尝试
  • 检查 IIS 日志文件 (C:\inetpub\logs\LogFiles)。您可能会找到错误的线索。

希望这对您有所帮助,就像过去对我所做的一样。 在最坏的情况下,尝试使用新的 IIS 设置 VM 并部署在那里。 然后交叉检查。