【问题标题】:proper implementation of "windows" authentication in web api?在 web api 中正确实现“windows”身份验证?
【发布时间】:2018-09-07 19:07:49
【问题描述】:

我创建了一个仅用于公司网络的 Web Api 2 应用。我已经阅读了有关 Web API 中的 Windows 身份验证的信息,所以这似乎是可能的。但我需要为此找出正确的实现方式。我在我的 Web.config 中包含了以下 xml:

<system.web>
  <authentication mode="Windows" />   
</system.web>

我似乎记得老式网络表单应用程序中的某种类型的事件挂钩。像 BeginRequest() 这样的东西,可以在呈现页面之前进行安全检查。我在我的一个控制器方法中包含以下代码行作为第一行,但返回的值似乎只是一个没有任何有意义信息的空对象:

var identity = HttpContext.Current.User.Identity as WindowsIdentity;

Web API 2 是否支持 Windows 身份验证?我错过了一步吗?如果我提交来自 Postman 的一般测试请求,Windows 身份验证是否有效?我也试过这段代码,但得到了一个类似的空对象:

var x = RequestContext.Principal;

我隐约记得像“启用集成安全性”这样的 IIS 设置。你能指定确切的设置吗?如果我在 IIS Express 上运行应用程序,我能做到这一点吗?

更新

我按照以下答案之一中提到的 IIS Express 的步骤操作,但我在原始帖子中提供的代码示例仍然没有得到填充的用户对象。我还更新了 applicationhost.config 文件以关闭匿名身份验证:

<anonymousAuthentication enabled="false" userName="" />

更新后,我通过 Postman 重新提交了测试请求,但出现以下错误:

    <h3>HTTP Error 401.2 - Unauthorized</h3>
    <h4>You are not authorized to view this page due to invalid authentication headers.</h4>
</div>
<div class="content-container">
    <fieldset>
        <h4>Most likely causes:</h4>
        <ul>
            <li>No authentication protocol (including anonymous) is selected in IIS.</li>
            <li>Only integrated authentication is enabled, and a client browser was used that does not support integrated authentication.</li>
            <li>Integrated authentication is enabled and the request was sent through a proxy that changed the authentication headers before they reach the Web server.</li>
            <li>The Web server is not configured for anonymous access and a required authorization header was not received.</li>
            <li>The "configuration/system.webServer/authorization" configuration section may be explicitly denying the user access.</li>
        </ul>
    </fieldset>
</div>
<div class="content-container">
    <fieldset>
        <h4>Things you can try:</h4>
        <ul>
            <li>Verify the authentication setting for the resource and then try requesting the resource using that authentication method.</li>
            <li>Verify that the client browser supports Integrated authentication.</li>
            <li>Verify that the request is not going through a proxy when Integrated authentication is used.</li>
            <li>Verify that the user is not explicitly denied access in the "configuration/system.webServer/authorization" configuration section.</li>
            <li>Check the failed request tracing logs for additional information about this error. For more information, click 
                <a href="http://go.microsoft.com/fwlink/?LinkID=66439">here</a>.
            </li>
        </ul>
    </fieldset>
</div>

我是否需要使用某种类型的特殊标头配置我的 Postman 请求才能使其正常工作?

【问题讨论】:

    标签: c# .net asp.net-web-api asp.net-web-api2 windows-authentication


    【解决方案1】:

    除了前面的答案,我们还需要在跨域请求中传递credentials

    服务器端(Web API):

    [EnableCors] 属性上将SupportsCredentials 属性设置为true

    [EnableCors(origins: "http://exampleclient.com", headers: "*", 
    methods: "*", SupportsCredentials = true)]
    

    客户端 (UI):

    XMLHttpRequest.withCredentials 设置为 true

    jQuery:

    $.ajax({
      type: 'get',
      url: 'http://www.example.com/api/auth',
      xhrFields: {
        withCredentials: true
      }
    

    角度:

    this.http.get('http://www.example.com/api/auth', { withCredentials: true }).subscribe((resp: any) => {
      console.log(resp)
    }
    

    XMLHttpRequest:

    var xhr = new XMLHttpRequest();
    xhr.open('get', 'http://www.example.com/api/auth');
    xhr.withCredentials = true;
    

    【讨论】:

      【解决方案2】:

      如果您使用的是IIS Express,则需要更新applicationhost.config 文件。

      这是 IIS 配置工具的文件版本,您可以在其中配置 Web 服务器本身。您可以在以下目录中找到此文件:

      %userprofile%\documents\iisexpress\config\applicationhost.config
      

      %userprofile%\my documents\iisexpress\config\applicationhost.config
      

      找到后,将其更新为:

      <windowsAuthentication enabled="true">
          <providers>
              <add value="Negotiate" />
              <add value="NTLM" />
          </providers>
      </windowsAuthentication>
      

      对于 IIS:

      1. 选择您的应用程序
      2. 双击 - “身份验证”
      3. 启用 Windows 身份验证
      4. 重启 IIS 服务器

      查看更多details

      【讨论】:

      • 我根据您的反馈更新了我的原始帖子。请查看“更新”标题下的更新信息。
      【解决方案3】:

      使用本地域用户并用于 Intranet 站点的 Windows 身份验证。

      例子:

      我实现了一个带有固定路由路径的TestAuthentication 方法/动作。对于演示,我还没有包含 Authorize 属性。代码检查ApiControllerUser 属性。这包含与Thread.CurrentPrincipalHttpContext.Current.User 相同的数据。确保 IIS 中的匿名身份验证已禁用,否则 Identity.Name 将为空。

      public class WinAuthController : ApiController
      {
          [HttpGet]
          [Route("api/testauthentication")]
          public IHttpActionResult TestAutentication()
          {
              Debug.Write("AuthenticationType:" + User.Identity.AuthenticationType);
              Debug.Write("IsAuthenticated:" + User.Identity.IsAuthenticated);
              Debug.Write("Name:" + User.Identity.Name);
      
              if (User.Identity.IsAuthenticated)
              {
                  return Ok("Authenticated: " + User.Identity.Name);
              }
              else
              {
                  return BadRequest("Not authenticated");
              }
          }
      }
      

      在 Web.config 文件中:

      <system.web>
         <authentication mode="Windows" />
       </system.web> 
      

      在 IE 中,您可以使用“工具”>“Internet 选项”>“高级”检查设置,然后查找“启用 Windows 集成身份验证”设置。当您转到选项卡安全性,然后是 Intranet 和自定义级别时,您会在底部找到一个设置,指定 IE 是自动登录还是提示输入用户名和密码。

      请访问以下链接,WEP API Windows 身份验证有正确的步骤:

      http://www.scip.be/index.php?Page=ArticlesNET38&Lang=EN

      【讨论】:

      • 谢谢!对于核心 2.2 并在 IIS 中运行它,我真的只需要从您上面提到的小型 web.config 部分添加三行。因为我的控制器不是继承自 ApiController,而是 ControllerBase,类属性为 [ApiController],所以我确实需要将输出类型更改为 IActionResult。再次感谢!
      【解决方案4】:

      以下是在 web api 中为本地和服务器 (IIS) 配置 windows 身份验证的步骤。

      1) 本地

      a) 在 windows 认证模式下创建 web api 项目,步骤如下:

      选择ASP.Net Web Application后,选择Web API模板,在右侧点击Change Authentication按钮,选择 Windows 身份验证

      b) 对于现有的 web api 项目,只需在您的 applicationhost.config 文件中添加以下行。

      <location path="YourProjectName">
              <system.webServer>
                  <security>
                      <authentication>
                          <anonymousAuthentication enabled="false" />
                          <windowsAuthentication enabled="true" />
                      </authentication>
                  </security>
              </system.webServer>
          </location>
      

      2) 对于服务器 (IIS)

      要在 IIS 中托管应用程序后运行 Windows 身份验证,只需在 web.config 节点内的 web.config 文件中添加以下行:

      <authentication mode="Windows" />
          <authorization>
            <allow verbs="OPTIONS" users="?" />
            <deny users="?" />
          </authorization>
      

      在这两种情况下,只需在代码中使用以下几行代码即可证明 Windows 身份验证正常工作:

      if(User.Identity.IsAuthenticated)
      {
          //do work
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-04
        • 1970-01-01
        • 2017-11-26
        • 2014-04-06
        • 1970-01-01
        • 2014-07-03
        • 1970-01-01
        相关资源
        最近更新 更多