Single sign on using AzureAD in ASP.NET 5

  • 2021-06-29 10:45:58
  • OfStack

Title: Although authentication authorization can continue to follow ASP.NET Identity in ASP.NET 5, it is also easy to integrate third-party services that support standard protocols, such as Azure Active Directory.

In fact, it is very simple to integrate AzureAD in ASP.NET 5 and use it to authenticate and authorize.Because: first, Azure Active Directory provides OAuth 2.0, OpenId Connect 1.0, SAML and WS-Federation 1.2 standard protocol interfaces;Second, Microsoft has ported the OWIN middleware integrated with OpenId Connect in ASP.NET 5.Therefore, integration is easy as long as the package "Microsoft.AspNet.Authentication.OpenIdConnect" is referenced in the ASP.NET 5 project and the connection information for AzureAD is configured correctly.

The general steps are as follows:

1. Add the configuration information of AzureAD to the config.json file:


"AzureAd": {
  "ClientId": "[Enter the clientId of your application as obtained from portal, e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]",
  "Tenant": "[Enter the name of your tenant, e.g. contoso.onmicrosoft.com]",
  "AadInstance": "https://login.microsoftonline.com/{0}", // This is the public instance of Azure AD
  "PostLogoutRedirectUri": https://localhost:44322/
}

2, Modify project.json to introduce OpenIdConnect's middleware:


"Microsoft.AspNet.Authentication.OpenIdConnect": "1.0.0-*"

3, add in the ConfigureServices method in Startup:


// OpenID Connect Authentication Requires Cookie Auth
services.Configure<ExternalAuthenticationOptions>(options =>
{
  options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});

4, add in the Configure method in Startup:


// Configure the OWIN Pipeline to use Cookie Authentication
app.UseCookieAuthentication(options => 
{
  // By default, all middleware are passive/not automatic. Making cookie middleware automatic so that it acts on all the messages.
  options.AutomaticAuthentication = true;

});

// Configure the OWIN Pipeline to use OpenId Connect Authentication
app.UseOpenIdConnectAuthentication(options =>
{
  options.ClientId = Configuration.Get("AzureAd:ClientId");
  options.Authority = String.Format(Configuration.Get("AzureAd:AadInstance"), Configuration.Get("AzureAd:Tenant"));
  options.PostLogoutRedirectUri = Configuration.Get("AzureAd:PostLogoutRedirectUri");
  options.Notifications = new OpenIdConnectAuthenticationNotifications
  {
    AuthenticationFailed = OnAuthenticationFailed,
  };
});

5, Startup's OnAuthenticationFailed method is:


private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
  notification.HandleResponse();
  notification.Response.Redirect("/Home/Error?message=" + notification.Exception.Message);
  return Task.FromResult(0);
}

6, add an Controller named AccountController:


public class AccountController : Controller
{
  // GET: /Account/Login
  [HttpGet]
  public IActionResult Login()
  {
    if (Context.User == null || !Context.User.Identity.IsAuthenticated)
      return new ChallengeResult(OpenIdConnectAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = "/" });
    return RedirectToAction("Index", "Home");
  }

  // GET: /Account/LogOff
  [HttpGet]
  public IActionResult LogOff()
  {
    if (Context.User.Identity.IsAuthenticated)
    {
      Context.Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationScheme);
      Context.Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationScheme);
    }
    return RedirectToAction("Index", "Home");
  }
}

The above code can also be found in my Fork full sample project: https://github.com/heavenwing/WebApp-OpenIdConnect-AspNet5

[Update: 2015-07-16]
If you encounter a situation where [Authorize] is added but cannot automatically go to the login page, you need to:


app.UseOpenIdConnectAuthentication(options => {
  options.AutomaticAuthentication = true;
});

See: https://github.com/aspnet/Security/issues/357#issuecomment-120834369

The above is the whole content of this article, I hope you like it.


Related articles: