Over a million developers have joined DZone.

ASP.NET Core RC1, OpenIdConnect, JWT, and Angular 2 SPA (Part 1)

In the hope of documenting some of my own recent experiences integrating ASP.NET Core and Angular 2 with Microsoft’s microservices framework Service Fabric, I’ll dive into specific code areas which have proven fiddley. First though, we’ll configure CookieAuthentication, OpenIdConnectAuthentication, JwtBearerAuthentication, MVC, & SPA routes in our ASP.NET Core Web project Startup.cs file.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Working with ASP.NET Core and Angular 2 (at the time of my writing this) may feel like a trail-blazing experience, especially given the lack of documentation and stability in the underlying frameworks, libraries, and tools, leading to lost time in debugging and searching for answers.

In the hope of documenting some of my own recent experiences integrating these technologies and Microsoft’s microservices framework Service Fabric, I’ll dive into specific code areas which have proven fiddley. To start off, I should preface that the version of ASP.NET Core I’m currently targeting is RC1 and thus, some bugs and workarounds will not apply to subsequent framework versions. Moreover, the Service Fabric version targeted is Service Fabric SDK (version 2.0.217) and Service Fabric Runtime (version 5.0.217).

To begin, we’ll start by configuring CookieAuthentication, OpenIdConnectAuthentication, JwtBearerAuthentication, MVC, & SPA routes in our ASP.NET Core Web project Startup.cs file.

Note that the below code supports multi-tenant Azure AD authentication and is meant for development scenarios as ValidateIssuer and RequireHttpsMetadata are both set to false for simplicity.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    if (env.IsDevelopment())
    {
    app.UseBrowserLink();
    app.UseDeveloperExceptionPage();
    }

    app.UseIISPlatformHandler();
    app.UseStaticFiles();

    app.UseCookieAuthentication(options =>
    {
        options.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.AutomaticAuthenticate = true;
        options.AutomaticChallenge = true;
        options.CookieSecure = CookieSecureOption.Never;
        // The default setting for cookie expiration is 14 days. SlidingExpiration is set to true by default
        options.ExpireTimeSpan = TimeSpan.FromHours(1);
        options.SlidingExpiration = true;
    });

    var acmeOptions = app.ApplicationServices.GetService<IOptions<AcmeOptions>>().Value;

    app.UseOpenIdConnectAuthentication(options =>
    {
        options.AutomaticAuthenticate = true;
        options.AutomaticChallenge = true;
        options.ClientId = acmeOptions.AzureAd.ClientId;
        options.Authority = AcmeConstants.AuthEndpointPrefix + "common/";
        options.PostLogoutRedirectUri = acmeOptions.AzureAd.PostLogoutRedirectUri;
        options.CallbackPath = AcmeRouteConstants.LoginCallbackRoute;
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.AuthenticationScheme = OpenIdConnectDefaults.AuthenticationScheme;
        options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false };
        options.RequireHttpsMetadata = false;
        options.Events = new OpenIdConnectAuthenticationEvents(acmeOptions.AzureAd)
        {
            OnAuthenticationFailed = context => OpenIdConnectAuthenticationEvents.GetFailedResponse(context)
        };
    });

    app.UseJwtBearerAuthentication(options =>
    {
        options.AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme;
        options.Audience = acmeOptions.AzureAd.JwtAudience;
        options.AutomaticAuthenticate = true;
        options.AutomaticChallenge = true;
        options.Authority = AcmeConstants.Security.AuthEndpointPrefix + "common/";
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,
        };
        options.RequireHttpsMetadata = false;
        options.Events = new JwtBearerAuthenticationEvents
        {
            OnAuthenticationFailed = context => JwtBearerAuthenticationEvents.GetFailedResponse(context)
        };
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute(
        name: "webapi",
        template: "api/{controller}/{action}/{id?}");

        routes.MapSpaFallbackRoute("spa-fallback", new { controller = "Home", action = "Index" });
    });
}


Apart from both JWT and OpenIdConnect support, of interest is the implementation of custom event overrides via the OpenIdConnectAuthenticationEvents and JwtBearerAuthenticationEvents classes. As OnAuthenticationFailed cannot be overridden within the derived event classes, we wire up our custom logic as below:

OnAuthenticationFailed = context => OpenIdConnectAuthenticationEvents.GetFailedResponse(context)

OnAuthenticationFailed = context => JwtBearerAuthenticationEvents.GetFailedResponse(context)


In Part 2, we’ll upgrade our code to ASP.NET Core RC2 and add support for Swagger and AutoRest.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
asp.net core ,jwt ,swagger ,service fabric ,microsoft

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}