取决于运行时配置的授权属性

时间:2019-10-09 23:02:05

标签: c# asp.net asp.net-core authorization asp.net-core-3.0

我有一个.Net Core 3.0 Web API,其配置如下:

services.AddAuthentication(x =>
  {
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  })
  .AddJwtBearer(x =>
  {
    ...
  });

services.AddAuthorizationCore(options =>
  {
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
      .RequireAuthenticatedUser()
      .Build();
  });

然后在控制器中启用它,如:

[Authorize(Roles = "Admin,Technician")]
public IActionResult CreateFoo([FromBody] Foo foo)

也可以使用[AllowAnonymous]禁用某些api端点。

该产品支持多种环境,并且一个端点需要是匿名的,也可以根据运行时变量进行授权;当前正在使用自定义“ ASPNETCORE_ENVIRONMENT”选项。

我已经看到.net安全人员的this评论,但是如果我实施了自定义策略,它将禁止匿名访问。

如果应用程序在特定环境中运行,允许匿名访问的最简单方法是什么?

2 个答案:

答案 0 :(得分:0)

AuthorizeAttribute只是AuthorizationFilterAttribute的实现。您可以创建自己的实现,该实现将绕过某些环境的身份验证:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class EnvironmentSpecificAutorizeAttribute : AuthorizeAttribute
{
    public string AllowAnonymousEnvironment { get; set; }

    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        // if currentEnv == AllowAnonymousEnvironment 
        //    return 
        // else
        //    base.HandleUnauthorizedRequest(actionContext);
    }
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        // same logic as above
        base.OnAuthorization(actionContext);
    }

    public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        // same logic as above
        return base.OnAuthorizationAsync(actionContext, cancellationToken);
    }
}

您可能会在this thread

中找到其他建议

答案 1 :(得分:0)

如果我理解您的问题,那么您可以创建一个自定义属性,并始终在应用程序在特定环境中运行时向用户授予访问权限?

   public class CustomEnvRequirement : AuthorizationHandler<CustomEnvRequirement>, IAuthorizationRequirement
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomEnvRequirement requirement)
        {
            string currentEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            // Allow Anonymous when the current env is development.
            if (currentEnv.ToLowerInvariant().Equals("development"))
            {
                context.Succeed(requirement);
            }
            else if (currentEnv.ToLowerInvariant().Equals("production"))
            {
                // TODO: add more authorization logic.

            }
            return Task.CompletedTask;
        }
    }

这是要添加的Custom属性

 [Authorize(Policy = "CustomEnv")]

        public IActionResult Index()
        {
            return this.View();
        }

此外,请确保在startup.cs中进行配置

  services.AddAuthorization(options =>
            {
                options.AddPolicy("CustomEnv",
                    policy => policy.Requirements.Add(new CustomEnvRequirement()));
            });