c# - 手动 Windows 身份验证

标签 c# asp.net .net odata ntlm

我目前正在尝试弄清楚如何在我们的 ASP.NET 应用程序中执行手动 Windows 身份验证。问题是我们有一个 OData 服务正在运行,并使用 FormsAuthentication 提供通用登录机制并允许 OData 的 PUT 和 DELETE 动词,包括表单重定向。

但是,对于一些客户,我们已经集成了 Windows 身份验证,以允许他们的用户与事件目录顺利集成。现在的问题是我们希望能够在不破坏 Odata 服务的情况下切换身份验证方法,因为我们依赖它。

我们正在尝试做的是使用 IhttpModule 模仿 Windows 身份验证机制。到目前为止,我们能够打开和关闭该功能,并且在发出请求时我们会收到挑战。我不知道的是如何使用从浏览器接收到的信息对事件目录进行身份验证:

这是我们用来从当前请求中提取 NTLM 信息的代码:

/// <summary>
/// <para>Determines whether the current <see cref="HttpRequest"/> is a NTML challenge.</para>
/// </summary>
/// <param name="request">The <see cref="HttpRequest"/> to evaluate.</param>
/// <param name="header">The output header to authenticate.</param>
/// <returns>True if the current <see cref="HttpRequest"/> is considered a NTML challenge.</returns>
 protected bool IsNtlmChallenge(HttpRequest request, out string header)
 {
      const string headerName = @"Authorization";
      if (request.Headers.AllKeys.Contains(headerName))
      {
           header = request.Headers[headerName];
           return true;
      }

      header = string.Empty;
      return false;
 }

这允许我们从请求中提取 header 。我现在需要知道的是如何在事件目录上使用它执行身份验证。

这是我们用来提取信息的逻辑:

// Check if we need to handle authentication through Windows authentication or not.
if (WindowsAuthentication)
{
    string encryptedHeader;

    // If this is a challenge from the client, perform the Windows Authentication using the 
    // information stored inside the header.
    if(IsNtlmChallenge(HttpContext.Current.Request, out encryptedHeader))
    {
         /* how to authenticate here with the encrypted header? */
    }

    HttpContext.Current.Response.AddHeader("WWW-Authenticate", "NTLM");
    HttpContext.Current.Response.StatusCode = 401;
    return;
}

希望有人能提供我需要的答案。

最佳答案

好的,

根据收到的关于我的问题的评论,我想出了以下解决方案来绕过我遇到的问题。我知道这不是一个干净的解决方案,但至少它对我们有用。

  • 创建一个在您的应用程序中运行的新 Web 应用程序
  • 此子应用程序依赖于 Windows 身份验证
    • 禁用匿名身份验证和表单例份验证
  • 创建处理 Windows 身份验证的 Login.aspx 页面
  • 我们在登录后生成一个cookie并重定向到原始应用
  • 原始应用识别 cookie 并带走用户。

这要求我们为两个应用程序生成相同的加密和解密 key 。这可以使用 IIS 管理器中的机器 key 模块为您的应用程序进行设置。 如果两个应用程序的 key 不相同,则 cookie 的编码/解码过程将失败。我们将它们设置为使用 SHA1 自动生成,但两个应用程序使用相同的 key 。

现在我们检查原始登录页面上的设置,如果需要 Windows 身份验证,则重定向到子应用程序的登录页面并在那里执行登录。然后我们重定向回原始登录页面并使用 cookie 继续。

这会导致在进行初始登录时进行一些重定向,但之后应用程序运行一如既往的流畅。

关于c# - 手动 Windows 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8989577/

相关文章:

c# - .NET/C# 与 Python 互操作

c# - C#-程序添加一个额外的'找到'的地方

c# - 从 aspx 设置多语言页面标题

.net - SQL 大型表上的 sql azure 超时

javascript - 加密 (cryptojs) - 解密 (.NET)

.net - 错误消息 "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

c# - 数字后修剪字符串

c# - 使用数组初始值设定项

c# - 多线程程序锁定 List<Stack<Person>> 的内部 Stack。这可以吗?

c# - Response.End() 后刷新页面内容