Skip to content

Instantly share code, notes, and snippets.

@siacomuzzi
Last active September 24, 2018 01:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save siacomuzzi/4fa48e32932473348fd2 to your computer and use it in GitHub Desktop.
Save siacomuzzi/4fa48e32932473348fd2 to your computer and use it in GitHub Desktop.
[AUTH0] ASP.NET Web Api: accept a JWT signed with RS256 algorithm

With Auth0, you can specify the algorithm used to sign your JWT tokens:

So in scenarios when you are signing JWTs with RSRS256 algorithm, you need to perform some changes in your ASP.NET Web Api in order to validate them properly.

NOTE: You can download your .cer file from https://{YOU}.auth0.com/cer endpoint.

ASP.NET Web Api (OWIN)

From app.UseJwtBearerAuthentication method, just replace SymmetricKeyIssuerSecurityTokenProvider with X509CertificateSecurityTokenProvider specifying your public signing key:

app.UseJwtBearerAuthentication(
  new JwtBearerAuthenticationOptions
  {
    AuthenticationMode = AuthenticationMode.Active,
    AllowedAudiences = new[] { audience },
    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
    {
      new X509CertificateSecurityTokenProvider(issuer, new X509Certificate2("PATH_TO_YOUR_PUBLIC_CERTIFICATE.cer")),
      // new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
    }
  });

Regular ASP.NET Web Api

Since JWT nuget v1.3.2 does not support RS256 algorithm, you need to replace it with System.IdentityModel.Tokens.Jwt nuget:

Install-Package System.IdentityModel.Tokens.Jwt

Go to App_Start\JsonWebTokenValidationHandler.cs and configure a JwtSecurityTokenHandler instance inside SendAsync method:

try
{
    SecurityToken securityToken;
    var tokenHandler = new JwtSecurityTokenHandler();
    var validationParameters = new TokenValidationParameters()
    {
      ValidAudience = this.Audience,
      ValidIssuer = this.Issuer,
      IssuerSigningKey = new X509SecurityKey(new X509Certificate2("PATH_TO_YOUR_PUBLIC_CERTIFICATE.cer"))
    };
    
    Thread.CurrentPrincipal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);
    
    if (HttpContext.Current != null)
    {
        HttpContext.Current.User = Thread.CurrentPrincipal;
    }
}
catch (SecurityTokenValidationException ex)
{
    errorResponse = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex);
}
catch (Exception ex)
{
    errorResponse = request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}

And remove the App_Start\JsonWebToken.cs file.

@JakobBlomberg
Copy link

I've tried this for ASP.NET Web Api (OWIN) but instead of using a .cer file I created a certificate based on just the Public Signing Key stored in a string and I get a valid certificate but cannot authenticate request to my Api. Any pointers?

@nordquist
Copy link

Without using a .cer file;

            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)
                    },
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        IssuerSigningKeyResolver = (a, b, c, d) => new X509SecurityKey(certificate),
                        ValidAudience = audience,
                        ValidIssuer = issuer
                    }
                }
            );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment