使用JWT在Owin上使用RSA进行身份验证

时间:2016-09-14 09:12:37

标签: c# asp.net-web-api rsa owin jwt

使用Owin中间件在我的Web API 2中考虑此代码:

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),
                }
            }
        );
    }
}

我可以从我的IDP中获取一个Bearer令牌,并在jwt.io中对其进行测试,结果如下:

Verified token

Issuer从代码到经过验证的令牌匹配。

ClientId从代码到经过验证的令牌(sub)匹配。

Audience从代码到经过验证的令牌匹配。

出于某种原因 - 但是每次请求都会拒绝令牌(401 Unauthorized),我无法理解为什么。我的请求包含Authorization标头,其中包含我可以使用jwt.ioBearer ey..)验证的相同承载令牌。如果它有任何区别我使用Auth0。我还可以提一下,我已经尝试下载公共证书并使用该文件而不是仅使用具有相同结果的公钥字符串。

1 个答案:

答案 0 :(得分:1)

设置TokenValidationParameters实例的JwtBearerAuthenticationOptions属性有助于解决问题:

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