In development, staging and production, my controllers use the [Authorize] attribute to make sure only authorized users have access to the methods. This obviously requires connection to an authentication service.
However, me and my team travel a lot on trains and planes where there's unreliable WIFI service. Removing these attributes for development on a plane trip and then putting them back in for production isn't a workable solution. I would like to have an option to configure the web service so that it does nothing when trying to authenticate so that we can still develop on long trips. I've seen some custom authentication schemes, but is there a simple way to simply 'do nothing' or a quick example of a simple custom authentication scheme that does nothing?
OK, worked this out from some more complicated examples:
public class LocalAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public LocalAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Create an empty claims identity and pass it off as a valid user. This is only valid in a local build environment to bypass the
// web-based authentication service.
var principal = new ClaimsPrincipal(new ClaimsIdentity(Array.Empty<Claim>(), this.Scheme.Name));
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, this.Scheme.Name)));
}
}
And in the startup.cs
serviceCollection.AddAuthentication(options => options.DefaultAuthenticateScheme = "Local")
.AddScheme<AuthenticationSchemeOptions, LocalAuthenticationHandler>("Local", null);