"
 
 
 
ASP.NET (snapshot 2017) Microsoft documentation and samples

External Authentication Services with ASP.NET Web API (C#)

by Robert McMurray

Visual Studio 2013 and ASP.NET 4.5.1 expand the security options for Single Page Applications (SPA) and Web API services to integrate with external authentication services, which include several OAuth/OpenID and social media authentication services: Microsoft Accounts, Twitter, Facebook, and Google.

In This Walkthrough

Prerequisites

To follow the examples in this walkthrough, you need to have the following:

## Using External Authentication Services

The abundance of external authentication services that are currently available to web developers help to reduce development time when creating new web applications. Web users typically have several existing accounts for popular web services and social media websites, therefore when a web application implements the authentication services from an external web service or social media website, it saves the development time that would have been spent creating an authentication implementation. Using an external authentication service saves end users from having to create another account for your web application, and also from having to remember another username and password.

In the past, developers have had two choices: create their own authentication implementation, or learn how to integrate an external authentication service into their applications. At the most basic level, the following diagram illustrates a simple request flow for a user agent (web browser) that is requesting information from a web application that is configured to use an external authentication service:

In the preceding diagram, the user agent (or web browser in this example) makes a request to a web application, which redirects the web browser to an external authentication service. The user agent sends its credentials to the external authentication service, and if the user agent has successfully authenticated, the external authentication service will redirect the user agent to the original web application with some form of token which the user agent will send to the web application. The web application will use the token to verify that the user agent has been successfully authenticated by the external authentication service, and the web application may use the token to gather more information about the user agent. Once the application is done processing the user agent’s information, the web application will return the appropriate response to the user agent based on its authorization settings.

In this second example, the user agent negotiates with the web application and external authorization server, and the web application performs additional communication with the external authorization server to retrieve additional information about the user agent:

Visual Studio 2013 and ASP.NET 4.5.1 make integration with external authentication services easier for developers by providing built-in integration for the following authentication services:

The examples in this walkthrough will demonstrate how to configure each of the supported external authentication services by using the new ASP.NET Web Application template that ships with Visual Studio 2013.

[!NOTE] If necessary, you may need to add your FQDN to the settings for your external authentication service. This requirement is based on security constraints for some external authentication services which require the FQDN in your application settings to match the FQDN that is used by your clients. (The steps for this will vary greatly for each external authentication service; you will need to consult the documentation for each external authentication service to see if this is required and how to configure these settings.) If you need to configure IIS Express to use an FQDN for testing this environment, see the Configuring IIS Express to use a Fully Qualified Domain Name section later in this walkthrough.

## Creating a Sample Web Application

The following steps will lead you through creating a sample application by using the ASP.NET Web Application template, and you will use this sample application for each of the external authentication services later in this walkthrough.

Start Visual Studio 2013 select New Project from the Start page. Or, from the File menu, select New and then Project.

When the New Project dialog box is displayed, select Installed Templates and expand Visual C#. Under Visual C#, select Web. In the list of project templates, select ASP.NET Web Application. Enter a name for your project and click OK.

When the New ASP.NET Project is displayed, select the SPA template and click Create Project.

Wait as Visual Studio 2013 creates your project.

When Visual Studio 2013 has finished creating your project, open the Startup.Auth.cs file that is located in the App_Start folder.

When you first create the project, none of the external authentication services are enabled in Startup.Auth.cs file; the following illustrates what your code might resemble, with the sections highlighted for where you would enable an external authentication service and any relevant settings in order to use Microsoft Accounts, Twitter, Facebook, or Google authentication with your ASP.NET application:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using Microsoft.AspNet.Identity;
   5:  using Microsoft.AspNet.Identity.EntityFramework;
   6:  using Microsoft.Owin.Security.Cookies;
   7:  using Microsoft.Owin.Security.OAuth;
   8:  using Owin;
   9:  using WebApplication1.Providers;
  10:   
  11:  namespace WebApplication1
  12:  {
  13:      public partial class Startup
  14:      {
  15:          public const string ExternalCookieAuthenticationType = CookieAuthenticationDefaults.ExternalAuthenticationType;
  16:          public const string ExternalOAuthAuthenticationType = "ExternalToken";
  17:   
  18:          static Startup()
  19:          {
  20:              PublicClientId = "self";
  21:   
  22:              IdentityManagerFactory = new IdentityManagerFactory(IdentityConfig.Settings, () => new IdentityStore());
  23:   
  24:              CookieOptions = new CookieAuthenticationOptions();
  25:   
  26:              OAuthOptions = new OAuthAuthorizationServerOptions
  27:              {
  28:                  TokenEndpointPath = "/Token",
  29:                  AuthorizeEndpointPath = "/api/Account/ExternalLogin",
  30:                  Provider = new ApplicationOAuthProvider(PublicClientId, IdentityManagerFactory, CookieOptions)
  31:              };
  32:          }
  33:   
  34:          public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
  35:   
  36:          public static CookieAuthenticationOptions CookieOptions { get; private set; }
  37:   
  38:          public static IdentityManagerFactory IdentityManagerFactory { get; set; }
  39:   
  40:          public static string PublicClientId { get; private set; }
  41:   
  42:          // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
  43:          public void ConfigureAuth(IAppBuilder app)
  44:          {
  45:              // Enable the application to use cookies to authenticate users
  46:              app.UseCookieAuthentication(CookieOptions);
  47:   
  48:              // Enable the application to use a cookie to store temporary information about a user logging in with a third party login provider
  49:              app.UseExternalSignInCookie(ExternalCookieAuthenticationType);
  50:   
  51:              // Enable the application to use bearer tokens to authenticate users
  52:              app.UseOAuthBearerTokens(OAuthOptions, ExternalOAuthAuthenticationType);
  53:   
  54:              // Uncomment the following lines to enable logging in with third party login providers
  55:              //app.UseMicrosoftAccountAuthentication(
  56:              //    clientId: "",
  57:              //    clientSecret: "");
  58:   
  59:              //app.UseTwitterAuthentication(
  60:              //    consumerKey: "",
  61:              //    consumerSecret: "");
  62:   
  63:              //app.UseFacebookAuthentication(
  64:              //    appId: "",
  65:              //    appSecret: "");
  66:   
  67:              //app.UseGoogleAuthentication();
  68:          }
  69:      }
  70:  }

When you press F5 to build and debug your web application, it will display a login screen where you will see that no external authentication services have been defined.

In the following sections, you will learn how to enable each of the external authentication services that are provided with ASP.NET in Visual Studio 2013.

## Enabling Facebook Authentication

Using Facebook authentication requires you to create a Facebook developer account, and your project will require an application ID and secret key from Facebook in order to function. For information about creating a Facebook developer account and obtaining your application ID and secret key, see https://go.microsoft.com/fwlink/?LinkID=252166.

Once you have obtained your application ID and secret key, use the following steps to enable Facebook authentication for your web application:

  1. When your project is open in Visual Studio 2013, open the Startup.Auth.cs file:

  2. Locate the highlighted section of code:

    [!code-csharpMain]
       1:  // Uncomment the following lines to enable logging in with third party login providers
       2:  //app.UseMicrosoftAccountAuthentication(
       3:  //    clientId: "",
       4:  //    clientSecret: "");
       5:   
       6:  //app.UseTwitterAuthentication(
       7:  //   consumerKey: "",
       8:  //   consumerSecret: "");
       9:   
      10:  //app.UseFacebookAuthentication(
      11:  //   appId: "",
      12:  //   appSecret: "");
      13:   
      14:  //app.UseGoogleAuthentication();
  3. Remove the “//” characters to uncomment the highlighted lines of code, and then add your application ID and secret key. Once you have added those parameters, you can recompile your project:

    [!code-csharpMain]
       1:  // Uncomment the following lines to enable logging in with third party login providers
       2:  //app.UseMicrosoftAccountAuthentication(
       3:  //    clientId: "",
       4:  //    clientSecret: "");
       5:   
       6:  //app.UseTwitterAuthentication(
       7:  //   consumerKey: "",
       8:  //   consumerSecret: "");
       9:   
      10:  app.UseFacebookAuthentication(
      11:     appId: "426f62526f636b73",
      12:     appSecret: "57686f6120447564652c2049495320526f636b73");
      13:   
      14:  //app.UseGoogleAuthentication();
  4. When you press F5 to open your web application in your web browser, you will see that Facebook has been defined as an external authentication service:

  5. When you click the Facebook button, your browser will be redirected to the Facebook login page:

  6. After you enter your Facebook credentials and click Log in, your web browser will be redirected back to your web application, which will prompt you for the User name that you want to associate with your Facebook account:

  7. After you have entered your user name and clicked the Sign up button, your web application will display the default home page for your Facebook account:

## Enabling Google Authentication

Google is by far the easiest of the external authentication services to enable because it doesn’t require a developer account, nor does it require additional information like your application ID or secret key as the other external authentication services necessitate.

To enable Google authentication for your web application, use the following steps:

  1. When your project is open in Visual Studio 2013, open the Startup.Auth.cs file:

  2. Locate the highlighted section of code:

    [!code-csharpMain]
       1:  // Uncomment the following lines to enable logging in with third party login providers
       2:  //app.UseMicrosoftAccountAuthentication(
       3:  //    clientId: "",
       4:  //    clientSecret: "");
       5:   
       6:  //app.UseTwitterAuthentication(
       7:  //   consumerKey: "",
       8:  //   consumerSecret: "");
       9:   
      10:  //app.UseFacebookAuthentication(
      11:  //   appId: "",
      12:  //   appSecret: "");
      13:   
      14:  //app.UseGoogleAuthentication();
  3. Remove the “//” characters to uncomment the highlighted line of code, and then recompile your project:

    [!code-csharpMain]
       1:  // Uncomment the following lines to enable logging in with third party login providers
       2:  //app.UseMicrosoftAccountAuthentication(
       3:  //    clientId: "",
       4:  //    clientSecret: "");
       5:   
       6:  //app.UseTwitterAuthentication(
       7:  //   consumerKey: "",
       8:  //   consumerSecret: "");
       9:   
      10:  //app.UseFacebookAuthentication(
      11:  //   appId: "",
      12:  //   appSecret: "");
      13:   
      14:  app.UseGoogleAuthentication();
  4. When you press F5 to open your web application in your web browser, you will see that Google has been defined as an external authentication service:

  5. When you click the Google button, your browser will be redirected to the Google login page:

  6. After you enter your Google credentials and click Sign in, Google will prompt you to verify that your web application has permissions to access your Google account:

  7. When you click Accept, your web browser will be redirected back to your web application, which will prompt you for the User name that you want to associate with your Google account:

  8. After you have entered your user name and clicked the Sign up button, your web application will display the default home page for your Google account:

## Enabling Microsoft Authentication

Microsoft authentication requires you to create a developer account, and it requires a client ID and client secret in order to function. For information about creating a Microsoft developer account and obtaining your client ID and client secret, see https://go.microsoft.com/fwlink/?LinkID=144070.

Once you have obtained your consumer key and consumer secret, use the following steps to enable Microsoft authentication for your web application:

  1. When your project is open in Visual Studio 2013, open the Startup.Auth.cs file:

  2. Locate the highlighted section of code:

    [!code-csharpMain]
       1:  // Uncomment the following lines to enable logging in with third party login providers
       2:  //app.UseMicrosoftAccountAuthentication(
       3:  //    clientId: "",
       4:  //    clientSecret: "");
       5:   
       6:  //app.UseTwitterAuthentication(
       7:  //   consumerKey: "",
       8:  //   consumerSecret: "");
       9:   
      10:  //app.UseFacebookAuthentication(
      11:  //   appId: "",
      12:  //   appSecret: "");
      13:   
      14:  //app.UseGoogleAuthentication();
  3. Remove the “//” characters to uncomment the highlighted lines of code, and then add your client ID and client secret. Once you have added those parameters, you can recompile your project:

    [!code-csharpMain]
       1:  // Uncomment the following lines to enable logging in with third party login providers
       2:  app.UseMicrosoftAccountAuthentication(
       3:      clientId: "426f62526f636b73",
       4:      clientSecret: "57686f6120447564652c2049495320526f636b73");
       5:   
       6:  //app.UseTwitterAuthentication(
       7:  //   consumerKey: "",
       8:  //   consumerSecret: "");
       9:   
      10:  //app.UseFacebookAuthentication(
      11:  //   appId: "",
      12:  //   appSecret: "");
      13:   
      14:  //app.UseGoogleAuthentication();
  4. When you press F5 to open your web application in your web browser, you will see that Microsoft has been defined as an external authentication service:

  5. When you click the Microsoft button, your browser will be redirected to the Microsoft login page:

  6. After you enter your Microsoft credentials and click Sign in, you will be prompted to verify that your web application has permissions to access your Microsoft account:

  7. When you click Yes, your web browser will be redirected back to your web application, which will prompt you for the User name that you want to associate with your Microsoft account:

  8. After you have entered your user name and clicked the Sign up button, your web application will display the default home page for your Microsoft account:

## Enabling Twitter Authentication

Twitter authentication requires you to create a developer account, and it requires a consumer key and consumer secret in order to function. For information about creating a Twitter developer account and obtaining your consumer key and consumer secret, see https://go.microsoft.com/fwlink/?LinkID=252166.

Once you have obtained your consumer key and consumer secret, use the following steps to enable Twitter authentication for your web application:

  1. When your project is open in Visual Studio 2013, open the Startup.Auth.cs file:

  2. Locate the highlighted section of code:

    [!code-csharpMain]
       1:  // Uncomment the following lines to enable logging in with third party login providers
       2:  //app.UseMicrosoftAccountAuthentication(
       3:  //    clientId: "",
       4:  //    clientSecret: "");
       5:   
       6:  //app.UseTwitterAuthentication(
       7:  //   consumerKey: "",
       8:  //   consumerSecret: "");
       9:   
      10:  //app.UseFacebookAuthentication(
      11:  //   appId: "",
      12:  //   appSecret: "");
      13:   
      14:  //app.UseGoogleAuthentication();
  3. Remove the “//” characters to uncomment the highlighted lines of code, and then add your consumer key and consumer secret. Once you have added those parameters, you can recompile your project:

    [!code-csharpMain]
       1:  // Uncomment the following lines to enable logging in with third party login providers
       2:  //app.UseMicrosoftAccountAuthentication(
       3:  //    clientId: "",
       4:  //    clientSecret: "");
       5:   
       6:  app.UseTwitterAuthentication(
       7:     consumerKey: "426f62526f636b73",
       8:     consumerSecret: "57686f6120447564652c2049495320526f636b73");
       9:   
      10:  //app.UseFacebookAuthentication(
      11:  //   appId: "",
      12:  //   appSecret: "");
      13:   
      14:  //app.UseGoogleAuthentication();
  4. When you press F5 to open your web application in your web browser, you will see that Twitter has been defined as an external authentication service:

  5. When you click the Twitter button, your browser will be redirected to the Twitter login page:

  6. After you enter your Twitter credentials and click Authorize app, your web browser will be redirected back to your web application, which will prompt you for the User name that you want to associate with your Twitter account:

  7. After you have entered your user name and clicked the Sign up button, your web application will display the default home page for your Twitter account:

## Additional Information

For additional information about creating applications that use OAuth and OpenID, see the following URLs:

### Combining External Authentication Services

For greater flexibility, you can define multiple external authentication services at the same time - this allows your web application’s users to use an account from any of the enabled external authentication services:

### Configuring IIS Express to use a Fully Qualified Domain Name

Some external authentication providers do not support testing your application by using an HTTP address like http://localhost:port/. To work around this issue, you can add a static Fully Qualified Domain Name (FQDN) mapping to your HOSTS file and configure your project options in Visual Studio 2013 to use the FQDN for testing/debugging. To do so, use the following steps:

Where WebApplication1 is the name of your project and bindingInformation contains the port number and FQDN that you want to use for your testing.

### How to Obtain your Application Settings for Microsoft Authentication

Linking an application to Windows Live for Microsoft Authentication is a simple process. If you have not already linked an application to Windows Live, you can use the following steps:

  1. Browse to https://go.microsoft.com/fwlink/?LinkID=144070 and enter your Microsoft account name and password when prompted, then click Sign in:

  2. Enter the name and language of your application when prompted, and then click I accept:

  3. On the API Settings page for your application, enter the redirect domain for your application and copy the Client ID and Client secret for your project, and then click Save:

### Optional: Disable Local Registration

The current ASP.NET local registration functionality does not prevent automated programs (bots) from creating member accounts; for example, by using a bot-prevention and validation technology like CAPTCHA. Because of this, you should remove the local login form and registration link on the login page. To do so, open the _Login.cshtml page in your project, and then comment out the lines for the local login panel and the registration link. The resulting page should like like the following code sample:

[!code-htmlMain]

   1:  <!-- ko with: login -->
   2:  <hgroup class="title">
   3:      <h1>Log in</h1>
   4:  </hgroup>
   5:  <div class="row-fluid">
   6:      @*<section class="span7">
   7:          <form>
   8:              <fieldset class="form-horizontal">
   9:                  <legend>Use a local account to log in.</legend>
  10:                  <ul class="text-error" data-bind="foreach: errors">
  11:                      <li data-bind="text: $data"></li>
  12:                  </ul>
  13:                  <div class="control-group">
  14:                      <label for="UserName" class="control-label">User name</label>
  15:                      <div class="controls">
  16:                          <input type="text" name="UserName" data-bind="value: userName, hasFocus: true" />
  17:                          <span class="text-error" data-bind="visible: userName.hasError, text: userName.errorMessage"></span>
  18:                      </div>
  19:                  </div>
  20:                  <div class="control-group">
  21:                      <label for="Password" class="control-label">Password</label>
  22:                      <div class="controls">
  23:                          <input type="password" name="Password" data-bind="value: password" />
  24:                          <span class="text-error" data-bind="visible: password.hasError, text: password.errorMessage"></span>
  25:                      </div>
  26:                  </div>
  27:                  <div class="control-group">
  28:                      <div class="controls">
  29:                          <label class="checkbox">
  30:                              <input type="checkbox" name="RememberMe" data-bind="checked: rememberMe" />
  31:                              <label for="RememberMe">Remember me?</label>
  32:                          </label>
  33:                      </div>
  34:                  </div>
  35:                  <div class="form-actions no-color">
  36:                      <button type="submit" class="btn" data-bind="click: login, disable: loggingIn">Log in</button>
  37:                  </div>
  38:                  <p><a href="#" data-bind="click: register">Register</a> if you don't have a local account.</p>
  39:              </fieldset>
  40:          </form>
  41:      </section>*@
  42:      <section class="span5">
  43:          <h2>Log in using another service</h2>
  44:          <div data-bind="visible: loadingExternalLogin">Loading...</div>
  45:          <div data-bind="visible: !loadingExternalLogin()">
  46:              <div class="message-info" data-bind="visible: !hasExternalLogin()">
  47:                  <p>
  48:                      There are no external authentication services configured. See <a href="http://go.microsoft.com/fwlink/?LinkId=252166">this article</a>
  49:                      for details on setting up this ASP.NET application to support logging in via external services.
  50:                  </p>
  51:              </div>
  52:              <form data-bind="visible: hasExternalLogin">
  53:                  <fieldset class="form-horizontal">
  54:                      <legend>Use another service to log in.</legend>
  55:                      <p data-bind="foreach: externalLoginProviders">
  56:                          <button type="submit" class="btn" data-bind="text: name, attr: { title: 'Log in using your ' + name() + ' account' }, click: login"></button>
  57:                      </p>
  58:                  </fieldset>
  59:              </form>
  60:          </div>
  61:      </section>
  62:  </div>
  63:  <!-- /ko -->

Once the local login panel and the registration link have been disabled, your login page will only display the external authentication providers that you have enabled:





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/security/external-authentication-services.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>