【发布时间】:2020-07-21 21:28:21
【问题描述】:
我正在尝试在我的应用中实现两种身份验证方案。在具有授权属性的控制器中,我设置了控制器必须用来进行身份验证的方案。 注册身份验证:
启动:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureAuthentication();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
app.UseAuthorization();
}
}
AuthenticationExtensions.cs:
public static class AuthenticationExtensions
{
public static IServiceCollection ConfigureAuthentication(this IServiceCollection services)
{
services.AddAuthentication(AuthConstants.DefaultScheme)
.AddScheme<AuthenticationSchemeOptions, DefaultSchemeHandler>(AuthConstants.DefaultScheme, AuthConstants.DefaultScheme, null)
.AddScheme<AuthenticationSchemeOptions, IdentityAuthenticationHandler>(AuthConstants.IdentityScheme, AuthConstants.IdentityScheme, null);
services.AddAuthorization(options =>
{
options.AddPolicy("IdentityAuthPolicy", policy =>
{
policy.AuthenticationSchemes.Add(AuthConstants.IdentityScheme);
policy.RequireAuthenticatedUser();
});
});
return services;
}
}
在控制器中,我定义了要使用的身份验证方案:
[Authorize(AuthenticationSchemes = AuthConstants.IdentityScheme)]
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{}
问题:应用程序在失败后尝试使用默认方案进行身份验证,尝试在授权属性中指定的方案。我希望应用程序使用我在授权属性中定义的唯一身份验证方案。另外,我尝试使用策略,但结果是一样的。
【问题讨论】:
-
你试过不带参数的
AddAuthentication()吗?而且在使用策略的时候,有没有使用[Authorize(Policy = "IdentityAuthPolicy")]这样的属性? -
是的,我试过了,但是其他请求无法授权,因为他们不知道如何授权,我不想在每个控制器上设置授权方案。使用 Policy 我得到相同的结果。
-
好的,在你的
Startup类Configure()方法中添加app.UseAuthorization();吗?您在测试期间没有看到任何错误日志? -
否则您可以编辑您的问题以包含您的 Startup
ConfigureServices()和Configure()方法吗? (当然要隐藏任何敏感信息) -
是的,我确实使用了 app.UseAuthentication()、app.UseAuthorization()。用启动文件更新了问题。
标签: c# authentication