用于开发和生产的.NET Core API条件验证属性

aho*_*try 11 c# asp.net api asp.net-core angular

简而言之,是否可以在我的API上放置基于环境的授权属性,以便在开发中关闭授权限制并在生产中重新启用?

我有一个单独的Angular 2项目,我希望将其称为.NET Core API.我们创建了一个单独的项目,因此我们可以在vscode中打开Angular 2项目并调试typescript.完成后,出于安全原因,我们将构建项目并将其放在.NET Core项目中.

我们的问题是在调试阶段,我们无法连接到API,因为它们是两个独立的项目,而我们的Angular 2项目没有Active Directory..NET Core项目当前具有身份验证属性,并且不允许访问API(401).如果我们能够在开发过程中关闭它并在生产过程中重新开启,那将是很好的.

我也对如何最好地解决这个问题提出任何其他建议.

[Authorize: (Only in Production)] <-- // something like this???
[Route("api/[controller]")]
public class TestController : Controller
{
    ...
Run Code Online (Sandbox Code Playgroud)

Mic*_*iey 18

ASP.NET核心授权基于策略.您可能已经看到,AuthorizeAttribute可以采用策略名称,以便知道要授权的请求需要满足哪些条件.我建议您阅读有关该主题的优秀文档.

回到您的问题,看起来您不使用特定策略,因此它使用默认策略,这要求默认情况下对用户进行身份验证.

你可以改变那种行为Startup.cs.如果您处于开发模式,则可以重新定义默认策略,使其不具有任何要求:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthorization(x =>
    {
        // _env is of type IHostingEnvironment, which you can inject in
        // the ctor of Startup
        if (_env.IsDevelopment())
        {
            x.DefaultPolicy = new AuthorizationPolicyBuilder().Build();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

更新

im1dermike在评论中提到AuthorizationPolicy至少需要一个要求,我们可以在这里看到.最近没有引入该代码,因此这意味着上面的解决方案一直被打破.

要解决这个问题,我们仍然可以利用RequireAssertion方法AuthorizationPolicyBuilder并添加虚拟需求.这看起来像:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthorization(x =>
    {
        // _env is of type IHostingEnvironment, which you can inject in
        // the ctor of Startup
        if (_env.IsDevelopment())
        {
            x.DefaultPolicy = new AuthorizationPolicyBuilder()
                .RequireAssertion(_ => true)
                .Build();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

这确保了我们在授权策略中至少有一个要求,并且我们知道它将始终通过.