Protecting Legacy .NET APIs with modern IdentityServer Tokens

Modern aspnetcore Web APIs are relatively easy to protect using Bearer Tokens issued by Duende IdentityServer. But there is a lot of legacy .NET framework code out there. This blog contains some simple tips to bring modern authentication to that world. Here is the big picture:

This example starts with a legacy API written classic Web API, .NET Framework 4.6.2, you know the kind that still had Global.asax and WebApiConfig.Register(config)…

GlobalConfiguration.Configure(WebApiConfig.Register);

In the Register method, you could do things like configure Routes, add Filters, and add MessageHandlers to your Http pipeline. Towards the end of the lifecycle of this platform, OWIN showed up. OWIN is also a way to add middleware to your pipeline, and if you are for instance using SignalR you might have some of that in your legacy app too. OWIN is configured using Startup classes, decorated with an OwinStartup attribute, something like this:

app.Map("/signalr", map =>
{
    map.UseCors(corsOptions);
    map.RunSignalR(hubConfiguration);
});

This is our key to adding Duende Identity Server authentication to some of our routes. In my case, all the existing API calls started with a route of /api, and I wanted to add some new APIs that were protected by bearer tokens issued by Identity Server. I put these routes under /auth :

app.Map("/auth/1.0", owin =>
{
    var authUrl = AppConfigHelper.Read(AppConfigKeys.IDENTITYSERVER_URL, "");
    var issuer = AppConfigHelper.Read(AppConfigKeys.IDENTITYSERVER_ISSUER, authUrl);
    var keyResolver = new OpenIdConnectSigningKeyResolver(authUrl);
    owin.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    ValidIssuer = issuer,
                    IssuerSigningKeyResolver =
                        (token, securityToken, kid, parameters) =>
                            keyResolver.GetSigningKey(kid)
                }
            });
});

There are a few details to explain in this code
Firstly, owin.UseJwtBearerAuthentication is what adds Microsoft’s OWIN middleware for bearer token authentication to this route. There is actually a IdentityServer middleware you can use instead, but it is not compatible with this older code base (here is a blog about that slightly more modern approach, if you are fortunate enough to be on a slightly newer code base). In our case, since we can’t use these newer packages, we need to drop all the way back to UseJwtBearerAuthentication.
Most of the code above is just concerned with setting up the URL to IdentityServer, which is needed because when incoming tokens are validated, we need to go get the public signing keys from IdentityServer’s published configuration endpoint (at /.well-known/openid-configuration – you can see an example here from Duende’s demo server), so we can validate the signature on the tokens. This work is done by the helper class OpenIdConnectSigningKeyResolver:

var keyResolver = new OpenIdConnectSigningKeyResolver(authUrl);

The constructor does some work, which I will discuss below, and then its GetSigningKey method is assigned to a lambda in JwtBearerAuthenticationOptions here:

IssuerSigningKeyResolver = (token, securityToken, kid, parameters) => keyResolver.GetSigningKey(kid)

This class can be found online, here is an adaptation I wrote:

using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using System.Linq;
using System.Net;
...
{
    public class OpenIdConnectSigningKeyResolver
    {
        private readonly OpenIdConnectConfiguration openIdConfig;
        public OpenIdConnectSigningKeyResolver(string authority)
        {
            var discoUrl = $"{authority.TrimEnd('/')}/.well-known/openid-configuration";
            var cm = new ConfigurationManager<OpenIdConnectConfiguration>(discoUrl,
                new OpenIdConnectConfigurationRetriever());
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
#if DEBUG
            ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
#endif
            openIdConfig = AsyncHelper.RunSync(async () => await cm.GetConfigurationAsync());
        }
        public SecurityKey[] GetSigningKey(string kid)
        {
            return new[] { openIdConfig.JsonWebKeySet.GetSigningKeys().FirstOrDefault(t => t.KeyId == kid) };
        }
    }
}

Some notes on this:
This codebase was before the age of await..async, so we need a little helper to make an async call, the AsyncHelper:

public static class AsyncHelper
{
    private static readonly TaskFactory _taskFactory = new
        TaskFactory(CancellationToken.None,
                    TaskCreationOptions.None,
                    TaskContinuationOptions.None,
                    TaskScheduler.Default);
    public static TResult RunSync<TResult>(Func<Task<TResult>> func)
        => _taskFactory
            .StartNew(func)
            .Unwrap()
            .GetAwaiter()
            .GetResult();
    public static void RunSync(Func<Task> func)
        => _taskFactory
            .StartNew(func)
            .Unwrap()
            .GetAwaiter()
            .GetResult();
}

Also, you will need to be using TLS 2:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

And in Development, we don’t want complaints about self signed development certificates:

#if DEBUG
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
#endif
openIdConfig = AsyncHelper.RunSync(async () => await cm.GetConfigurationAsync());

The key resolver uses the ConfigurationManager class to fetch the OpenIdConnect configuration from IdentityServers /.well-known/openid-configuration, and stores the results in a local variable.
Later, when a key is needed for token validation, it can be retrieved from that local variable by the call to GetSigningKey that we added to the Jwt configuration.

public SecurityKey[] GetSigningKey(string kid)
{
  return new[] { openIdConfig.JsonWebKeySet.GetSigningKeys().FirstOrDefault(t => t.KeyId == kid) };
}

With this OWIN middleware in place, I can now add an ApiController with an authorize attribute, and since the route starts with /auth, the bearer token will be validated.

[RoutePrefix("auth/1.0/mymethod")]
public class MyController : ApiController
{
  [HttpGet]
  [Route("")]
  [Authorize]
  public void MyMethod()
  {

Nuget package h**@#ll

One of the trickiest parts in getting new code to run in legacy apps is finding the right versions of dependencies – nuget packages – that will work with the old code. You can’t just add the latest versions of referenced packages. I found these package versions to be what did the trick for this combo of code:

<Reference Include="IdentityModel, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\IdentityModel.1.9.2\lib\net45\IdentityModel.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.JsonWebTokens, Version=5.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.IdentityModel.JsonWebTokens.5.3.0\lib\net461\Microsoft.IdentityModel.JsonWebTokens.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Logging, Version=5.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.IdentityModel.Logging.5.3.0\lib\net461\Microsoft.IdentityModel.Logging.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Protocol.Extensions, Version=1.0.2.33, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.IdentityModel.Protocol.Extensions.1.0.2.206221351\lib\net45\Microsoft.IdentityModel.Protocol.Extensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Tokens, Version=5.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.IdentityModel.Tokens.5.3.0\lib\net461\Microsoft.IdentityModel.Tokens.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin, Version=4.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Owin.4.2.0\lib\net45\Microsoft.Owin.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin.Cors">
<HintPath>..\..\packages\Microsoft.Owin.Cors.3.0.1\lib\net45\Microsoft.Owin.Cors.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Owin.Host.SystemWeb">
<HintPath>..\..\packages\Microsoft.Owin.Host.SystemWeb.3.0.1\lib\net45\Microsoft.Owin.Host.SystemWeb.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Owin.Security, Version=4.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Owin.Security.4.2.0\lib\net45\Microsoft.Owin.Security.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin.Security.Jwt, Version=4.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Owin.Security.Jwt.4.2.0\lib\net45\Microsoft.Owin.Security.Jwt.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin.Security.OAuth, Version=4.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Owin.Security.OAuth.4.2.0\lib\net45\Microsoft.Owin.Security.OAuth.dll</HintPath>
</Reference>
<Reference Include="System.IdentityModel.Tokens.Jwt, Version=5.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.IdentityModel.Tokens.Jwt.5.3.0\lib\net461\System.IdentityModel.Tokens.Jwt.dll</HintPath>
</Reference>

And these packages:

<package id="Microsoft.IdentityModel.JsonWebTokens" version="5.3.0" targetFramework="net462" />
<package id="Microsoft.IdentityModel.Logging" version="5.3.0" targetFramework="net462" />
<package id="Microsoft.IdentityModel.Tokens" version="5.3.0" targetFramework="net462" />
<package id="Microsoft.Owin" version="4.2.0" targetFramework="net462" />
<package id="Microsoft.Owin.Cors" version="3.0.1" targetFramework="net451" />
<package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net451" />
<package id="Microsoft.Owin.Security" version="4.2.0" targetFramework="net462" />
<package id="Microsoft.Owin.Security.Jwt" version="4.2.0" targetFramework="net462" />
<package id="Microsoft.Owin.Security.OAuth" version="4.2.0" targetFramework="net462" />
<package id="System.IdentityModel.Tokens.Jwt" version="5.3.0" targetFramework="net462" />

I hope some of this will come in handy if you find yourself in the same situation, shoehorning modern authentication into a legacy codebase!

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.