Consider this code in my Web API 2 using Owin middleware:
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
ConfigureAuthentication(app);
app.UseCors(CorsOptions.AllowAll);
WebApiConfig.Register(config);
app.UseWebApi(config);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
private static void ConfigureAuthentication(IAppBuilder app)
{
var issuer = "<<MyIssuer>>";
var audience = "<<MyAudience>>";
const string publicKeyBase64 = "<<MyPublicKeyBase64>>";
var certificate = new X509Certificate2(Convert.FromBase64String(publicKeyBase64));
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new X509CertificateSecurityTokenProvider(issuer, certificate),
}
}
);
}
}
I can get a Bearer token from my IDP and test it in jwt.io with the following result:
Issuer
matches from code to verified token.
ClientId
matches from code to verified token (sub
).
Audience
matches from code to verified token.
For some reason - the token is however rejected (401 Unauthorized) on every request and I just can´t get my head around why. My request includes the Authorization
header with the same bearer token I can verify using jwt.io
(Bearer ey..
). If it makes any difference I use Auth0. I can also mention that I have tried downloading the public cert and using the file instead of just using the public key string with the same result.