我正在开发一个使用 REST API 的本机应用程序。目前我的其余 api 受 JWT 持有者保护。我想限制客户端使用我的剩余 IP。这个想法是将客户端证书添加到每个客户端。就像我们想要认证客户端应用程序一样,同时使用该客户端对用户进行身份验证。 但是我无法合并CertificateAuthenticationDefaults 和JwtBearerDefaults。我的控制器上的 [Authorize] 属性只能接受 CertificateAuthenticationDefaults 或 JwtBearerDefaults,不能同时接受这两种方案。有解决这个问题的参考吗?
您可以在
AuthenticationSchemes
属性中设置多个 Authorize
。
假设这就是您添加令牌验证的方式:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
//This is the default one to check as JwtBearerDefaults.AuthenticationScheme(Bearer)
.AddJwtBearer(options =>
{
// handle token
})
// scheme name is Certificate
.AddCertificate(CertificateAuthenticationDefaults.AuthenticationScheme, options =>
{
// handle token
});
在Authorize属性中,可以将两者都设置为检查:
[HttpGet]
[Authorize(AuthenticationSchemes = $"{CertificateAuthenticationDefaults.AuthenticationScheme},{JwtBearerDefaults.AuthenticationScheme}")]
public IEnumerable<WeatherForecast> Get()
{
//...
}
当您指定多个方案时,它与
OR
一起使用意味着它将检查两者,如果其中之一成功验证令牌,它将允许请求进行。