使用智威汤逊在Owin
问题描述:
RSA身份验证在我的Web API 2,考虑以下代码使用Owin中间件:使用智威汤逊在Owin
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获得承载令牌和jwt.io结果如下测试:
Issuer
从代码到验证令牌的匹配。
ClientId
从代码到验证令牌的匹配(sub
)。
Audience
从代码到验证令牌的匹配。
出于某种原因 - 然而,令牌被拒绝(401未经授权)在每个请求上,我无法理解为什么。我的请求包括Authorization
标头和我可以使用jwt.io
(Bearer ey..
)验证的相同不记名标记。如果它有什么不同,我使用Auth0。我还可以提到,我已经尝试下载公共证书并使用该文件,而不是仅使用具有相同结果的公钥字符串。
答
设置JwtBearerAuthenticationOptions
实例TokenValidationParameters
财产帮助问题:
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
}
}
);
}
您的凭据不会在你的形象完全模糊;有可能读到钥匙,是否有人这么倾向。如果尚未流通,我建议撤销这些令牌。 – Rob
这实际上只是一个示例项目,并且键很久以前就已过期,但仍然感谢您的关注;) – Marcus