DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > ASP.NET Core RC1, OpenIdConnect, JWT, and Angular 2 SPA (Part 1)

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.

Andrej Medic user avatar by
Andrej Medic
·
Jun. 22, 16 · Web Dev Zone · Tutorial
Like (1)
Save
Tweet
4.07K Views

Join the DZone community and get the full member experience.

Join For Free

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.

ASP.NET ASP.NET Core JWT (JSON Web Token) AngularJS

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Is Cloud-Native Architecture?
  • A Guide to Understanding Vue Lifecycle Hooks
  • How to Use Geofences for Precise Audience Messaging
  • Top 20 Git Commands With Examples

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo