Asp.Net Core Web API – Bearer Authentication

Often people use Bearer Authentication for securing API requests. Normally everything works fine and you can send the token as header information and if the token is valid you can call the API without getting status code 401 unauthorized. In my case I could call the API once and while the second try I got 401 unauthorized. After hours of error searching I find my mistake. It’s very important to load the parts in startup.cs in the right order.

services.AddAuthentication
services.AddMvc

and

app.UseAuthentication
app.UseMvc

Authentication methods have to be called before Mvc methods to handle authentication early in the pipeline.

If you load it in the wrong order you might get a problem like me. Hope this hint helps somebody to save time 😉