Asp.net"禁用"开发环境中的身份验证

时间:2016-12-13 01:52:23

标签: asp.net-core

是否可以"禁用"在不改变逻辑的情况下在asp.net核心应用程序中进行身份验证?

我有一个.net网站,它使用外部身份服务器应用程序进行身份验证。 无论如何,我希望能够在我开发它时模拟身份验证(ASPNETCORE_ENVIRONMENT =开发),通过访问忽略授权属性的所有操作。

是否可以仅仅模拟服务集合中的某些服务?

4 个答案:

答案 0 :(得分:21)

在更新到Net Core 3.1时,mvc AllowAnonymousFilter不再对我们有用。我们发现有条件地添加自定义IAuthorizationHander是有条件地绕过身份验证的最简单方法。

例如

/// <summary>
/// This authorisation handler will bypass all requirements
/// </summary>
public class AllowAnonymous : IAuthorizationHandler
{
    public Task HandleAsync(AuthorizationHandlerContext context)
    {
        foreach (IAuthorizationRequirement requirement in context.PendingRequirements.ToList())
            context.Succeed(requirement); //Simply pass all requirements

        return Task.CompletedTask;
    }
}

然后有条件地在Startup.ConfigureServices中注册此处理程序。

private readonly IWebHostEnvironment _env;
public Startup(IWebHostEnvironment env)
{
    _env = env;
}

public void ConfigureServices(IServiceCollection services)
{
  {...}

  //Allows auth to be bypassed
  if (_env.IsDevelopment())
    services.AddSingleton<IAuthorizationHandler, AllowAnonymous>();
}

注意AddAuthenticationAddAuthorization服务仍按照产品代码注册和配置(很好)。

为了允许我们的单元测试绕过auth,我们添加了一个带有启动类的新匿名测试库,该类在没有任何条件的情况下添加了该行。很好,很简单!

答案 1 :(得分:10)

我在illucIT Blog找到了解决此问题的方法。

此代码必须有效:

if (env.IsDevelopment()) {
   services.AddMvc(opts =>
   {
      opts.Filters.Add(new AllowAnonymousFilter());
   });
} else {
   services.AddMvc();
}

答案 2 :(得分:5)

在没有更多详细信息的情况下给出详细答案很棘手,但我之前通过有条件注册来实现这一目标:

  • 外部认证中间件
  • 需要经过身份验证的请求的全局政策
它看起来像是:

//this is where I dont get a response on click
if(bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED ){
        CloseSheet.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN){

                }
                else if(event.getAction() == MotionEvent.ACTION_UP){
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                }
                else if(event.getAction() == MotionEvent.ACTION_CANCEL){
                }
                return true;
            }
        });
    }

就我而言,授权过滤器是全局应用的,因此MVC应用程序的每个操作都需要经过身份验证的用户。

如果您有不同的要求 - 某些操作的细粒度public class Startup { public Startup(IHostingEnvironment env) { Environment = env; } public IHostingEnvironment Environment { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(x => { if (!Environment.IsDevelopment()) { var authenticatedUserPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); x.Filters.Add(new AuthorizeFilter(authenticatedUserPolicy)); } }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); if (!Environment.IsDevelopment()) { // Register external authentication middleware } app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } 属性 - 那么您可以通过更改相关授权策略的构建方式来实现相同的结果。它们基本上根本不包含任何要求。

[Authorize]

答案 3 :(得分:4)

在ASP.NET Core 3.x和更高版本中,可以如下所示更改Startup.Configure()方法,以便将AllowAnonymousAttribute添加到控制器中:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...
    app.UseEndpoints(endpoints =>
    {
        if (env.IsDevelopment())
            endpoints.MapControllers().WithMetadata(new AllowAnonymousAttribute());
        else
            endpoints.MapControllers();
    });
}

请注意,这会将AllowAnonymousAttribute添加到所有控制器。 AllowAnonymousAttribute在文档中的描述:

指定此属性应用于的类或方法不需要授权。

相关问题