Porting to .NET Core (Part 4)

Home / Porting to .NET Core (Part 4)

Continuing my (old) series on porting to .NET Core, I am sharing some of my experiences of moving a production, legacy .NET 4.5.x application to .NET Core 2.2.  This was a interesting endeavor since the application itself had some really deep hooks into the older WebAPI/MVC pipeline.

Ripping out those hooks is like opening the proverbial can of worms ..

I’ve talked previously about sharing OWIN cookies/tokens between a .NET Core application and an .NET OWIN-based application.  However, if you’re migrating to .NET Core and not using OWIN for anything other than providing an authentication middleware based on OpenIdConnect, I find that’s it best to completely rid yourself of OWIN.  Don’t even attempt to salvage it with any compatibility shims or whatever..

public void Configuration(IAppBuilder app)
{
    var validationTokens = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false
    };

    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
    {
        AccessTokenFormat = new JwtFormat(
            validationTokens,
            new CustomOpenIdConnectCachingSecurityTokenProvider(
                "youroauthmetadataendpoint")),
    });
}

In NET. Core, we can use the built-in Authentication to achieve the same thing. Within our ConfigureServices method, to do the same thing as OWIN, this setup is added:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,
            ValidateAudience = false
        };

        // Equivalent of OpenIdConnectCachingSecurityTokenProvider
        options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(
            "your oauth metadata endpoint",
            new OpenIdConnectConfigurationRetriever())
        {
            RefreshInterval = new TimeSpan(0, 5, 0) //5 minutes
        };
    });

And, of course, in our Configure method, we have to UseAuthentication prior to (most) of the other Middleware.

That’s really it for porting this type of authentication form OWIN to .NET Core. In my case, the endpoint is Azure AD, but this should work with most OpenIdConnect endpoints that use JwtTokens.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.