This article describes how to disable authentication for ASP.NET Core 2.0.
ASP.NET Core JWT Authentication
I have some Rest API which I want to protect via JwtBearer token in production e.g.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public void ConfigureServices(IServiceCollection services) { ... services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(o => { o.Authority = authority; o.Audience = audience; o.RequireHttpsMetadata = false; }); services.AddMvc(); ... } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { ... app.UseAuthentication(); app.UseMvc(); ... } |
However in order to test the API, for development I totally want to disable authentication without having to remove all Authorizes in the Controllers.
First Attempt
If you however try something like this:
1 2 3 4 5 |
if (!env.IsDevelopment()) { ... services.AddAuthentication(options => ... } |
you will run into the following error:
An unhandled exception occurred while processing the request.
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.
Solution
It took the quite some time to figure out a valid solution. And it is very simpe as well…
What I ended up doing is this:
1 2 3 4 5 6 7 8 |
if (env.IsDevelopment()) { services.AddMvc(opts => { opts.Filters.Add(new AllowAnonymousFilter()); }); } else { services.AddMvc(); } |
Now everyone can access the API in development. Hope this helps someone solve this problem.
If you have any questions or further information, please leave a comment below.