Whenever I implement authentication and authorization with Azure AD in an ASP.NET Core application, in development environments I require a valid and configured account to sign in and get to the protected pages.
If the environment is development, I'd like to be able to run the app as if a user was signed in by default. For example, any User.Identity.IsAuthenticated value would be true, [Authorize] attributes would be ignored, any usages of IAuthorizationService would react as if the user was fully authorized. How could this be done? Or it would be equally good if when I press to sign in with Microsoft it just automatically "authenticates" on any computer.
I looked through some SO solutions, but they all seem to disable authentication. I can't disable it because if [Authorize] attribute is bypassed but User.Identity.IsAuthenticated returns false, code in my controllers and razor views would break. I want this so that when Selenium runs automatic tests for the UI it does not have to deal with signing into Microsoft, and that anyone who wants to run the app locally isn't required to have an account.
When signing in, I use the action from MicrosoftIdentity at /MicrosoftIdentity/Account/SignIn.
If it helps, here's my ConfigureServices method in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(Configuration.GetValue<double>("AzureAd:TimeoutInMinutes"));
options.SlidingExpiration = true;
});
RegisterAuthorizationPolicies(services);
services.Configure(OpenIdConnectDefaults.AuthenticationScheme, (Action<OpenIdConnectOptions>)(options =>
{
options.Events.OnTicketReceived = async context =>
{
// I run some code here that determines whether or not to allow the user to sign in.
return;
};
}));
services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
...
}