首页 > 解决方案 > .net core 3.0 使用 Policy、AuthenticationSchemes 授权属性

问题描述

我正在尝试在我的应用程序中实现两个身份验证方案。在具有授权属性的控制器中,我设置了控制器必须用来进行身份验证的方案。注册授权:

启动:

 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
{}

问题:应用程序在失败后尝试使用默认方案进行身份验证,尝试在授权属性中指定的方案。我希望应用程序使用我在授权属性中定义的唯一身份验证方案。另外,我尝试使用策略,但结果是一样的。

标签: c#authentication

解决方案


你应该:

  1. 添加控制器服务

  2. 通过添加路由相关的中间件来设置路由

  3. 先调用 app.UseAuthorization()before注册授权中间件app.UseAuthentication()

这是您的Startup课程代码的样子:

public void ConfigureServices(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();
        });
    });

    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();

    app.UseAuthorization();
    app.UseAuthentication();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

之后,使用AuthenticationSchemes属性的[Authorize]属性或其Policy属性:

[Authorize(AuthenticationSchemes = AuthConstants.IdentityScheme)]
//[Authorize(Policy = "IdentityAuthPolicy")]
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
}

推荐阅读