Adding external provider authentication

In the following section, we will showcase external provider authentication by using Facebook as an authentication provider.

Here is an overview of the control flow in this case:

  1. The user clicks on a dedicated external provider login button.
  2. The corresponding controller receives a request indicating which provider is needed, and then a challenge is initiated with the external provider.
  3. The external provider sends an HTTP callback (POST or GET) with a provider name, a key, and some user claims for the application.
  4. The claims are matched with the internal application user.
  5. If no internal user can be matched with the claims, the user is either redirected to a specific registration form or is rejected.
Note that the implementation steps are the same for all external providers if they support OWIN and ASP.NET Core Identity, and that you may even create your own providers and integrate them in the same way.

We are now going to implement external provider authentication via Facebook:

  1. Update the login form, and add a button called Login with Facebook directly after the standard Login button:
        <a id="btn-fblogin" asp-action="ExternalLogin"
asp-controller="Account" asp-route-Provider="Facebook"
class="btn btn-primary">Login with Facebook</a>
  1. Update the UserService class and the user service interface, and then add two new methods called GetExternalAuthenticationProperties and GetExternalLoginInfoAsync
        public async Task<AuthenticationProperties>
GetExternalAuthenticationProperties(string provider,
string redirectUrl) { return await Task.FromResult(
_signInManager.ConfigureExternalAuthentication
Properties(
provider, redirectUrl)); } public async Task<ExternalLoginInfo>
GetExternalLoginInfoAsync() { return await _signInManager.GetExternalLoginInfoAsync(); }

Add another new method called ExternalLoginSignInAsync

public async Task<SignInResult> ExternalLoginSignInAsync(
string loginProvider, string providerKey, bool
isPersistent) { _logger.LogInformation($"Sign in user with external login
{loginProvider} - {providerKey}"); return await _signInManager.ExternalLoginSignInAsync(
loginProvider, providerKey, isPersistent); }
  1. Update AccountController, and add a method called ExternalLogin : 
[AllowAnonymous] 
public async Task<ActionResult> ExternalLogin(string provider, string ReturnUrl) 
{ 
  var redirectUrl = Url.Action(nameof(ExternalLoginCallBack),
"Account", new { ReturnUrl = ReturnUrl }, Request.Scheme,
Request.Host.ToString()); var properties = await _userService.
GetExternalAuthenticationProperties(provider, redirectUrl); ViewBag.ReturnUrl = redirectUrl; return Challenge(properties, provider); }

In the same AccountController class, add another method called ExternalLoginCallBack

[AllowAnonymous] 
public async Task<IActionResult> ExternalLoginCallBack(string returnUrl, string remoteError = null) 
{ 
  if (remoteError != null) 
  { 
    ModelState.AddModelError(string.Empty, $"Error from external 
provider: {remoteError}"); ViewBag.ReturnUrl = returnUrl; return View("Login"); } var info = await _userService.GetExternalLoginInfoAsync(); if (info == null) return RedirectToAction("Login", new { ReturnUrl = returnUrl }); var result = await _userService.ExternalLoginSignInAsync(
info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { if (!string.IsNullOrEmpty(returnUrl)) return
Redirect(returnUrl); else return RedirectToAction("Index", "Home"); } if (result.IsLockedOut) return View("Lockout"); else return View("NotFound"); } }
  1. Register the Facebook middleware within the Startup class:
        services.AddAuthentication(options => { 
          options.DefaultScheme =
CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme =
CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme =
CookieAuthenticationDefaults.AuthenticationScheme; }).AddCookie().AddFacebook(facebook => { facebook.AppId = "123"; facebook.AppSecret = "123"; facebook.ClientId = "123"; facebook.ClientSecret = "123"; });
Note that you must update the Facebook middleware configuration and register your application with the Facebook developer portal before being able perform authenticated logins with a Facebook account.

Please go to https://developer.facebook.com for more information.

  1. Start the application, click on the Login with Facebook button, sign in with your Facebook credentials, and verify that everything is working as expected:

Congratulations on reaching this far and, with similar steps as before, you will be able to use other external providers such as Google, or indeed Microsoft, for authentication. Now, let's look at how we can implement two-factor authentication in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.51.36