Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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 ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

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.

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}