.NET Core 在本地开发期间绕过或关闭 [Authorize(Roles="")]

Vij*_*udi 7 c# .net-core asp.net-core asp.net-core-webapi asp.net-core-3.1

我有以下代码可以在本地开发期间绕过添加身份验证,我正在使用 Azure AD 和 .NET Core。

#if !DEBUG
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
               .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));
#endif
Run Code Online (Sandbox Code Playgroud)

但是,由于我的控制器受 Authorize 属性保护,因此如何在本地开发期间绕过 Controller 内的 Authorize 属性:

[Authorize(Roles = "Buyer")]
public class ProductController : ApiBaseController
{
}
Run Code Online (Sandbox Code Playgroud)

在 .NET Framework 中,我有以下代码来覆盖 Authorize 属性:

public class MyAuthorizeAttribute : AuthorizeAttribute
    {
     #if DEBUG
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return true;
        }
     #endif
    }
Run Code Online (Sandbox Code Playgroud)

.NET Core 的等效代码是什么?或者有没有其他方法可以覆盖 Startup.cs 类中的 Authorize 属性?

Vij*_*udi 0

感谢 Jeremy 的正确指导,我使用下面的代码使其正常工作:

在控制器类中,我使用基于策略的授权:

 [Authorize(Policy= "Buyer")]
 public class ProductController : ApiBaseController
 {
 }
Run Code Online (Sandbox Code Playgroud)

在start.cs中我们可以根据DEBUG条件添加身份验证和授权:

#if !DEBUG
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
               .AddMicrosoftIdentityWebApi(config.GetSection("AzureAd"));
#endif

            services.AddAuthorization(options =>
            {
                // policy for read access
                options.AddPolicy("Buyer", policy =>
                {
#if DEBUG
                    policy.RequireAuthenticatedUser();
#else
                    policy.RequireRole("Buyer");
#endif
                });
            });
Run Code Online (Sandbox Code Playgroud)

对于调试模式下的 RequireAuthenticatedUser(),我们使用以下代码在所有控制器上添加 AllowAnonymous 属性:

app.UseEndpoints(endpoints =>
            {
#if DEBUG
                endpoints.MapControllers().WithMetadata(new AllowAnonymousAttribute());
#else
                    endpoints.MapControllers();
#endif
            });
Run Code Online (Sandbox Code Playgroud)