六、使用窗体和 Windows 认证保护 Web API

本章将介绍如何使用窗体和 Windows 认证来保护 Web API。 您还将了解在 Web API 中使用 Forms 和 Windows 认证的优点和缺点。

在本章中,我们将涵盖以下主题:

  • 表单验证的工作
  • 在 Web API 中实现表单认证
  • 讨论 Windows 集成认证
  • 讨论了使用 Windows 集成认证机制的优缺点
  • 配置 Windows 认证
  • 讨论基本认证和 Windows 认证之间的区别
  • 在武士刀中启用 Windows 认证

表单验证工作

用户凭证将在 forms 认证中使用 HTML 表单提交给服务器。 这可以在 ASP 中使用.NET Web API,仅当它被 Web 应用使用时。 表单验证是在 asp.net 下构建的.NET,并使用 asp.net.NET 成员资格提供程序来管理用户帐户。 表单认证要求浏览器客户机将用户凭据传递给服务器。 它在请求中发送用户凭证,并使用 HTTP cookie 进行认证。

让我们列出表单验证的逐步过程,如下:

  1. 浏览器试图访问需要经过认证的请求的受限操作。
  2. 如果浏览器发送一个未经认证的请求,那么服务器将响应 HTTP 状态302 Found,并触发 URL 重定向到登录页面。
  3. 要发送经过认证的请求,用户输入用户名和密码,然后提交表单。
  4. 如果凭证是有效的,服务器响应 HTTP 302 状态码,该状态码发起浏览器将页面重定向到原始请求的 URL,并在响应中使用认证 cookie。
  5. 现在,来自浏览器的任何请求都包含认证 cookie,服务器将授予对任何受限资源的访问权。

在 Web API 中实现表单认证

要将凭据发送到服务器,我们需要提交一个 HTML 表单。 让我们在 ASP 中使用 HTML 表单或 HTML 视图。 净 MVC 应用。

在 ASP 中实现表单验证的步骤.NET MVC 应用如下:

  1. 在 Visual Studio 的Start页面中创建新项目
  2. 选择 Visual c# Installed Template 命名为Web
  3. 选择ASP.NET Web 应用在中心面板。
  4. Name the project as Chapter06.FormsAuthentication and click OK:

    Implementing Forms authentication in Web API

    图 1 -我们已经命名了 ASP.NET Web 应用”第六章。 FormsAuthentication”

  5. 新 ASP. net 中中选择MVC模板.NET 项目对话框。

  6. Tick Web API under Add folders and core references and press OK, leaving the Authentication to Individual User Accounts:

    Implementing Forms authentication in Web API

    图 2 -选择 MVC 模板,在添加文件夹和核心引用中检查 Web API

  7. Forms authentication configuration can be included in the web.config file, as follows:

    <system.web> <authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="30" /> </authentication> </system.web>

    在此配置中,我们将认证模式设置为"Forms",并配置了loginurl,以便应用在请求未经过认证时重定向到已配置的页面进行登录。

  8. Models文件夹中,添加一个名为Contact.cs的类,代码如下:

    namespace Chapter06.FormsAuthentication.Models { public class Contact { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } public string Mobile { get; set; } } }

  9. 添加一个名为ContactsController的 Web API 控制器,代码片段如下:

正如您在前面的代码中看到的,我们已经用[Authorize]属性装饰了ContactsController中的Get()动作。 因此,这个 Web API 操作只能由经过认证的请求访问。 这个操作的未经验证的请求将使浏览器重定向到登录页面,并允许用户注册或登录:

Implementing Forms authentication in Web API

图 3 -重定向登录页面认证

一旦登录,任何试图访问此操作的请求都将在经过认证后被允许。 这个是因为浏览器会自动发送会话 cookie,表单验证使用这个 cookie 来验证请求:

Implementing Forms authentication in Web API

图 4 -开发工具中显示的认证 Cookie

注意事项

由于表单认证发送未加密的凭证,所以使用 SSL 保护网站是非常重要的。 参考第二章为 ASP 启用 SSL.NET Web API学习如何为您的应用设置 SSL。

*# 什么是 Windows 集成认证?

集成 Windows 认证是一种基于 SPNEGO、Kerberos 和 NTLMSSP 协议的认证机制。 它处理 IIS、IE 和活动目录之间的连接的自动认证。

使用 Windows 集成认证机制的优缺点

首先让我们看看 Windows 认证的优点。 Windows 认证是在 IIS 中构建的。 它不随请求一起发送用户凭证。 这种认证机制最适合于 intranet 应用。

然而,有了这些优点,Windows 认证机制也没有什么缺点。 它需要 Kerberos, Kerberos 基于票据或 NTLM,后者是一种客户机应该支持的微软安全协议。 客户端 PC 必须在 active directory 域下。

配置 Windows 认证

让我们实现对 ASP 的 Windows 认证.NET MVC 应用以下的步骤:

  1. 在 Visual Studio 的Start页面中创建新项目
  2. 选择Visual c# Installed Templatenamed Web。
  3. 选择ASP.NET Web 应用在中心面板。
  4. Name the project Chapter06.WindowsAuthentication and click OK:

    Configuring Windows Authentication

    图 5 -我们已经命名了 ASP.NET Web 应用”第六章。 WindowsAuthentication”

  5. Change the Authentication mode to Windows Authentication:

    Configuring Windows Authentication

    图 6 -在更改认证窗口中选择 Windows 认证

  6. 新 ASP. net 中选择MVC模板.NET 项目对话框。

  7. Tick Web API under Add folders and core references and click OK:

    Configuring Windows Authentication

    图 7 -选择 MVC 模板,在添加文件夹和核心引用中检查 Web API

  8. 在 Models 文件夹下,添加一个名为Contact.cs的类,代码如下:

    namespace Chapter06.FormsAuthentication.Models { public class Contact { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } public string Mobile { get; set; } } }

  9. 添加一个名为ContactsController的 Web API 控制器,代码如下:

    ``` namespace Chapter06.FormsAuthentication.Api { public class ContactsController : ApiController { IEnumerable contacts = new List { new Contact { Id = 1, Name = "Steve", Email = "steve@gmail.com", Mobile = "+1(234)35434" }, new Contact { Id = 2, Name = "Matt", Email = "matt@gmail.com", Mobile = "+1(234)5654" }, new Contact { Id = 3, Name = "Mark", Email = "mark@gmail.com", Mobile = "+1(234)56789" } };

        [Authorize]
        // GET: api/Contacts
        public IEnumerable<Contact> Get()
        {
            return contacts;
        }
    }
    

    } ```

  10. The Get() action in ContactsController is decorated with the [Authorize] attribute. But in Windows authentication, any request is considered as authenticated request if the client relies on the same domain. So no explicit login process is required to send an authenticated request to call the Get() action.

    注意事项

    注意:Windows 认证配置在Web.config文件中,如下所示:

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

基本认证与 Windows 认证的区别

Windows 认证通过在 Windows 域中根据用户帐户验证凭据来验证用户。

基本认证验证表单中针对存储在数据库中的用户帐户提供的凭据。

在武士刀中启用 Windows 认证

Katana 是一个项目集合,通过System.WebSystem.Net.HttpListener的各种微软组件来支持 OWIN。

我们可以在基于 owen 的应用中插入 Web API,而不是依赖于System.Web文件。 这可以通过安装Microsoft.AspNet.WebApi.OwinNuGet 包来实现,它允许将 Web API 添加到中间件管道中。

按照以下步骤创建一个控制台应用,并在武士刀中启用 Windows 认证:

  1. 在 Visual Studio 的Start页面中创建新项目
  2. 选择Visual c# Installed Template命名Windows Desktop
  3. 在中间窗格中选择控制台应用
  4. Name the project as Chapter06.WindowsAuthenticationKatana and click OK:

    Enabling Windows authentication in Katana

    图 8 -我们将控制台应用命名为“第六章” WindowsAuthenticationKatana”

  5. Install NuGet Package named Microsoft.Owin.SelfHost from NuGet Package Manager:

    Enabling Windows authentication in Katana

    图 9 -安装名为 microsoft . owen . selfhost 的 NuGet 包

  6. 用以下代码片段添加一个 Startup 类:

    ``` namespace Chapter06.WindowsAuthenticationKatana { class Startup { public void Configuration(IAppBuilder app) { var listener = (HttpListener)app.Properties["System.Net.HttpListener"]; listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;

            app.Run(context =>
            {
                context.Response.ContentType = "text/plain";
                return context.Response.WriteAsync("Hello Packt Readers!");
            });
        }
    }
    

    } ```

  7. Program.cs的主功能中添加如下代码:

    using (WebApp.Start<Startup>("http://localhost:8001")) { Console.WriteLine("Press any Key to quit Web App."); Console.ReadKey(); }

  8. Now run the application and open http://localhost:8001/ in the browser, as shown in the following screenshot:

    Enabling Windows authentication in Katana

    图 10 -在浏览器中打开 Web App

  9. 如果使用 Fiddler 捕获请求,您将注意到请求头中有一个 Authorization Negotiate 条目。

  10. 尝试在 Fiddler 中调用http://localhost:8001/,您将得到一个带有WWW-Authenticate报头的401 Unauthorized响应,这表明服务器附加了使用 Kerberos 或 NTLM 的Negotiate协议,如下所示:

总结

瞧! 我们只是使用表单和 Windows 认证来保护我们的 Web API。

在本章中,您了解了表单认证的工作方式以及它是如何在 Web API 中实现的。

您还学习了配置 Windows 认证,了解了使用 Windows 认证的优缺点。

然后您学习了在 Katana 中实现 Windows 认证机制。

在下一章中,让我们看看如何使用外部认证服务(如 Facebook 和 Twitter)来保护 Web API。*