七、使用 ASP.NET Web API 使用外部认证服务

本章将帮助您理解启用 OAuth/OpenID 和社交媒体认证时需要使用外部认证服务。

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

  • 使用 OWIN 外部认证服务
  • 实现 Facebook 认证
  • 实现微博认证
  • 实现谷歌认证
  • 实现微软认证
  • 讨论验证

使用 OWIN 外部认证服务

使用外部认证服务进行认证可以减少实现内部认证机制所需的开发时间。 大多数网络用户在社交媒体网站上都有账户,比如 Facebook 和 Twitter,以及其他服务,比如微软和谷歌。 使用外部认证服务可以节省用户为您的 web 应用创建另一个帐户的时间。

ASP.NET 为外部认证服务(如 Facebook、Twitter、Microsoft 和谷歌)提供内置支持。

创建 ASP。 净 MVC 应用

让我们创建一个 ASP.NET MVC 应用来演示如何实现外部认证解决方案,如下:

  1. 在 Visual Studio 中从“开始”页创建新项目。
  2. 选择 Visual c# Installed Template,命名为 Web。
  3. 选择 ASP.NET Web 应用。
  4. Name the project as Chapter07.ExternalAuthentication and click OK:

    Creating an ASP.NET MVC Application

    图 1 -我们已经命名了 ASP.NET Web 应用作为“第 07 章。 ExternalAuthentication”

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

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

    Creating an ASP.NET MVC Application

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

  7. 将名为Contact.cs的模型类添加到 Models 文件夹中,代码如下:

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

  8. 添加一个名为ContactsController的 Web API 控制器,并用以下代码替换代码:

    ``` namespace Chapter07.ExternalAuthentication.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;
        }
    }
    

    } ```

我们刚刚创建了一个 ASP.NET MVC 应用,并添加了一个名为ContactsController的 Web API 控制器来提供一个联系人详细信息列表。 ContactsController中的Get操作被[Authorize]属性修饰,只能使用经过认证的请求调用。 现在,让我们逐个添加外部认证解决方案来验证请求。

实现 Facebook 认证

要将 Facebook 认证服务应用到我们的应用中,我们首先需要在 Facebook 中创建一个开发者帐户,然后使用该开发者帐户在 Facebook 上创建一个应用。 这个应用将为我们提供一个应用 ID 和一个密钥,以便在我们的应用中启用 Facebook 认证。 按照给定的步骤从 Facebook 获得密钥:

  1. 使用您的凭证登录到 Facebook。
  2. 导航到 Facebook 开发者网站(https://developers.facebook.com/)。
  3. Click the Register as a Developer menu item under the My Apps menu:

    Implementing Facebook authentication

    图 3 -从菜单中选择注册为开发人员

  4. Select Yes to accept the Facebook Platform Policy and Facebook Privacy Policy and click Register, which would successfully register you as a Facebook Developer. You can now add Facebook to your app or website:

    Implementing Facebook authentication

    图 4 -点击 Register 注册成为 Facebook 开发者

  5. Click Website in the Add a New App page:

    Implementing Facebook authentication

    图 5 -在 Add a New App 页面选择 Website

  6. Click Skip and Create App ID on the Quick Start for Website page:

    Implementing Facebook authentication

    图 6 -导航到 Skip and Create App ID 链接

  7. Provide Display Name and Namespace. Select Category under the model popup dialog. Then click the Create App ID button:

    Implementing Facebook authentication

    图 7 -导航到 Skip 和 Create App ID link

  8. Confirm the captcha as a security check by entering the text exactly in the same case, since it is case sensitive, and click Submit:

    Implementing Facebook authentication

    图 8 -为了安全起见,确认验证码

  9. Now the Dashboard for the created Facebook app will be shown with the details of the App ID, API Version, and App Secret key:

    Implementing Facebook authentication

    图 9 - App ID 和 Secret key 在仪表盘下可用

  10. Navigate to Settings and click on Add Platform:

    Implementing Facebook authentication

    图 10 - App ID 和 Secret key 在仪表盘下可用

  11. Click Website under the Select Platform model popup dialog:

    Implementing Facebook authentication

    图 11 -为平台选择网站

  12. Enter your website URL in Site URL under the Website panel that was added. You can also use localhost URL as Site URL during development:

    Implementing Facebook authentication

    图 12 -提供应用 URL

  13. 单击Save Changes按钮保存所做的更改。

  14. 复制App IDApp Secret Key值,以便配置应用代码。 当用户试图使用 Facebook 帐户登录时,这些值将从您的网站传递给 Facebook 提供商。
  15. 退出 Facebook 开发者网站。
  16. 打开 ASP.NET MVC 应用,我们在上一节中创建。
  17. 打开App_Start文件夹下的Startup.Auth.cs 类文件。
  18. 将复制的App IDApp Secret Key在以下代码中按照ConfigureAuth方法更新:

    app.UseFacebookAuthentication( appId: "", appSecret: "");

  19. Now, run the application and try to log in using Facebook by clicking the Facebook button. Your website will be redirected to Facebook in order to authenticate the login request:

    Implementing Facebook authentication

    图 13 -单击 Facebook 来验证用户以访问您的应用

  20. Facebook will confirm with the user whether they are fine with the app that may access the public profile information. Your public profile includes name, profile picture, age range, gender, language, country, and other public information:

    Implementing Facebook authentication

    图 14 -确认访问您的个人信息

  21. Clicking Okay will redirect you back to the application and you will be asked to provide your email ID in order to register the user who has logged in via Facebook, by associating his Facebook account. The redirect happens as we supplied a redirect URL for our application:

    Implementing Facebook authentication

    图 15 -通过注册你的电子邮件 id 来关联你的 Facebook 账户

实现 Twitter 认证

在实现 Facebook 认证时,我们还需要创建一个 Twitter 开发人员帐户,并需要从应用向 Twitter 提供消费者密钥和消费者秘密值,以便进行认证。

按照给定的步骤从您的应用的 Twitter 开发人员帐户中获取消费者密钥和秘密值:

  1. 登录您的 Twitter 账号(https://twitter.com/)。
  2. 导航到 Twitter 开发人员站点(https://dev.twitter.com/)。
  3. 向下滚动到页脚,点击Tools下的Manage Your Apps
  4. Click the Create New App button in the redirected page:

    Implementing Twitter authentication

    图 16 -创建你的 Twitter 应用

  5. Provide your Application Details such as Name, Description, Website, and Callback URL. Tick agree to the developer agreement in the Create an application page. The Callback URL is the URL of our application that Twitter needs to redirect to after the successful authentication:

    Implementing Twitter authentication

    图 17 -提供创建应用的细节

  6. 点击创建您的 Twitter应用按钮。

  7. 可以找到消费者关键秘密值,点击管理密钥和访问令牌下的应用设置【显示】细节部分的选项卡创建应用。 复制消费者密钥秘密值
  8. App_Start文件夹下,打开Startup.Auth.cs类文件。
  9. 更新复制的消费者密钥消费者秘密值,如下代码在ConfigureAuth方法下:

    app.UseTwitterAuthentication( consumerKey: "", consumerSecret: "");

  10. Run your application and click on the Twitter button in the following page to log in using Twitter:

    Implementing Twitter authentication

    图 18 -单击 Twitter 来验证用户

  11. Your application will redirect to Twitter for authentication. Click Sign In to authorize the Twitter app to use your account and authenticate the access to your application:

    Implementing Twitter authentication

    图 19 -通过单击 sign in 来授权您的应用

  12. You need to provide your email ID to register and associate your Twitter account:

    Implementing Twitter authentication

    图 20 -将 Twitter 应用与应用配置文件关联

  13. 退出 Twitter 网站。

实现谷歌认证

到目前为止,我们已经看到了如何通过 Facebook 和 Twitter 等社交媒体网站整合外部认证。 现在让我们看看如何集成谷歌认证。 我们需要在谷歌开发人员控制台中创建一个项目和一个创建客户端 ID 和秘密密钥,并且应该在我们的应用中配置这个客户端 ID 和秘密密钥。

按照给定的步骤从应用的谷歌开发控制台获取客户端 ID 和密钥值:

  1. 登录您的谷歌账号(https://www.google.com/)。
  2. 打开谷歌开发控制台站点(https://console.developers.google.com/)。
  3. Click Create Project:

    Implementing Google authentication

    图 21 -在谷歌开发人员控制台中创建项目

  4. Enter the Project Name and click the Create button:

    Implementing Google authentication

    图 22 -提供项目名称和创建

  5. 点击API&auth|API,使能谷歌+ API

  6. Click APIs & auth | Credentials and select the OAuth consent screen tab. Provide the Project Name and Save:

    Implementing Google authentication

    图 23 -提供你的电子邮件地址

  7. Select OAuth 2.0 client ID under Add credentials:

    Implementing Google authentication

    图 24 -在“添加凭证”按钮下拉框中选择 API 密钥 这张截图是 2015 年 9 月拍摄的

  8. Create client ID by selecting web application as Application Type and providing authorized JavaScript origins and redirect URIs:

    Implementing Google authentication

    图 25 -配置授权的应用类型、JavaScript 起源和重定向 uri

  9. The client ID and secret key will be shown on a modal popup, as follows:

    Implementing Google authentication

    图 26 -复制 Client ID 和 Secret key 值

  10. 复制ClientIDandSecret key

  11. App_Start文件夹下,打开Startup.Auth.cs类文件。
  12. 更新复制的客户端 IDSecret Key值,如下代码在ConfigureAuth方法下:
  13. 运行 web 应用,从外部认证服务登录页面使用谷歌登录。
  14. The web application will be redirected to Google for authentication. Click Allow to authorize the application to access the user profile and authenticate using your Google account:

    Implementing Google authentication

    图 27 -提供创建应用的细节

  15. You need to provide your email ID to register and associate your Google account:

    Implementing Google authentication

    图 28 -通过注册你的电子邮件 id 来关联你的谷歌账户

  16. 退出谷歌站点。

实现 Microsoft 认证

Microsoft 认证就像利用终端用户的企业账户来验证他们的身份。 我们需要创建一个应用并配置重定向 URL。 然后从 Microsoft 开发人员帐户的应用设置中复制客户端 ID 和密钥,并在我们的应用代码中配置它们。

按照给定的步骤从 Microsoft 开发人员门户获取客户端 ID 和密钥值:

登录到您的微软帐户(https://www.live.com/)。

  1. 导航到 Microsoft 开发人员中心站点(https://account.live.com/developers/applications/)。
  2. Provide the Application name and click the I accept button:

    Implementing Microsoft authentication

    图 29 -让你的应用使用微软帐户

  3. Click on API Settings and configure Redirect URLs:

    Implementing Microsoft authentication

    图 30 -为应用配置重定向 URL

  4. Click App Settings and copy the Client ID and Client Secret value:

    Implementing Microsoft authentication

    图 31 -复制客户端 ID 和 Secret Key 值

  5. App_Start文件夹下,打开Startup.Auth.cs类文件。

  6. 更新复制的客户端 IDSecret Key值,如下代码在ConfigureAuth方法下:
  7. 运行 web 应用,从外部认证服务登录页面使用 Microsoft 帐号登录。
  8. On clicking the Microsoft button for login, your application will redirect to Microsoft Live for authentication. Click Yes to authorize the application and authenticate the user that is using your Microsoft account:

    Implementing Microsoft authentication

    图 32 -允许你的应用从微软账户访问用户信息

  9. You need to provide your email ID to register and associate your Microsoft account:

    Implementing Microsoft authentication

    图 33 -通过注册你的电子邮件来关联你的微软账户

  10. 退出 Microsoft 站点。

讨论认证

在前面的部分中,我们已经看到了外部认证是如何执行的。 这一切都始于注册从外部认证提供者检索的用户详细信息。 在用户详细信息成功注册到我们的应用后,我们不需要再次在应用中存储用户详细信息。

这一次,外部认证提供者不会为了访问用户的公共概要信息而询问用户的权限,因为用户已经将权限授予了我们的应用。 因此,外部认证提供者将只验证用户,而我们的应用将绕过现有用户的注册过程。

总结

瞧! 我们只是使用外部认证机制来保护我们的 Web API。

在本章中,您了解了 OWIN 外部认证以及如何使用它来保护我们的 Web API。

您还学习了如何在外部认证服务(如 Facebook、Twitter、谷歌和 Microsoft)上注册为开发人员,并在那里创建一个应用,分别获取客户端 ID 和密钥以及消费者 ID 和密钥。

然后,您了解了如何配置从源代码中的外部认证服务复制的 ID 和密钥,以便在应用中实现外部认证。

最后,我们运行了应用并看到了外部认证的工作情况。

在下一章中,让我们学习如何保护我们的 Web API 免受跨站点请求伪造攻击。

让我们准备进攻吧!