Sachin Gandhi
Sachin Gandhi

Reputation: 1

Asp.net Core 3.1 MVC - Disable Authentication in Development Environment

We have integrated our code with Azure AD for authentication. As per our Azure AD policy, we even require to authenticate via MFA. Hence during development, we need to enter password & also MFA which is very frustrating.

Is it possible to disable authentication in development without removing [Authorize] tag Or can we add dummy principal object ?

Here is screen grab of our code in ConfigureServices in Startup class

enter image description here

I have seen couple of post but none of option works for us.

Please help us out. Thanks in Advance

Upvotes: 0

Views: 1889

Answers (1)

Allen Wu
Allen Wu

Reputation: 16478

In .net core 3.1, if the environment type is Development, you can add a custom IAuthorizationHander to conditionally bypass auth.

A sample in this answer:

/// <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;
    }
}

Then register this handler conditionally in 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>();
}

Upvotes: 1

Related Questions