Skip to content

Web App Middleware

Oleg Burov edited this page May 13, 2018 · 5 revisions

Here you will do a major part of wiring up the Auth0. You will start with adding authentication service to the service container, which makes it available within the Web App, and then enabling the authentication itself.

Visual Studio

In the file Startup.cs, modify the method ConfigureServices as shown below:

Add Authentication middleware

The method AddAuthentication registers the authentication services. It specifies the DefaultAuthenticateScheme, DefaultSignInScheme and DefaultChallengeScheme as the cookies. What this means is that when ASP.NET Core checks whether a user is authenticated, it will use the cookie authentication handler, which you need to register next.

public void ConfigureServices(IServiceCollection services)
{
  services.Configure<CookiePolicyOptions>(options =>
  ...

  services.AddAuthentication(options =>
  {
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  });
  
  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  ...
}

Add Cookie handler

The method AddCookie registers the cookie authentication handler.

public void ConfigureServices(IServiceCollection services)
{
  ...
  services.AddAuthentication(options =>
  {
    ...
  })  
  .AddCookie(options => options.LoginPath = "/Account/Signin");

  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  ...
}

Add OpenIdConnect handler

The method AddOpenIdConnect registers the OpenID Connect authentication handler.

public void ConfigureServices(IServiceCollection services)
{
  ...
  .AddCookie(options => options.LoginPath = "/Account/Signin")
  .AddOpenIdConnect("Auth0", options =>
  {
    options.Authority = $"https://{Configuration["Auth0:Domain"]}";    
    options.ClientId = Configuration["Auth0:ClientId"];
    options.ClientSecret = Configuration["Auth0:ClientSecret"];
    options.ResponseType = "code";

    options.Scope.Clear();
    options.Scope.Add("openid");

    options.CallbackPath = new PathString("/signin-auth0");
    options.ClaimsIssuer = "Auth0";
    options.SaveTokens = true;

    options.Events = new OpenIdConnectEvents
    {
      OnRedirectToIdentityProviderForSignOut = (context) =>
      {
        var logoutUri = $"https://{Configuration["Auth0:Domain"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}";

        var postLogoutUri = context.Properties.RedirectUri;
        if (!string.IsNullOrEmpty(postLogoutUri))
        {
          if (postLogoutUri.StartsWith("/"))
          {
            var request = context.Request;
            postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
          }

          logoutUri += $"&returnTo={Uri.EscapeDataString(postLogoutUri)}";
        }

        context.Response.Redirect(logoutUri);
        context.HandleResponse();

        return Task.CompletedTask;
      },
    };
  });

  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  ...
}

Enable Authentication service

In the file Startup.cs, modify the method Configure as shown below.

The method UseAuthentication adds authentication middleware to the request pipeline, which enables identity for the Web App.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  ...
  app.UseCookiePolicy();

  app.UseAuthentication();

  app.UseMvc(routes =>
  ...
}

What's next?

Web App - Login