使用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中对其进行测试,结果如下:
Issuer
从代码到经过验证的令牌匹配。
ClientId
从代码到经过验证的令牌(sub
)匹配。
Audience
从代码到经过验证的令牌匹配。
出于某种原因 - 但是每次请求都会拒绝令牌(401 Unauthorized),我无法理解为什么。我的请求包含Authorization
标头,其中包含我可以使用jwt.io
(Bearer ey..
)验证的相同承载令牌。如果它有任何区别我使用Auth0。我还可以提一下,我已经尝试下载公共证书并使用该文件而不是仅使用具有相同结果的公钥字符串。
答案 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
}
}
);
}