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!