2

(Environment: .net 6 web api) reference post: c# asp.net core Bearer error="invalid_token" solved my problem: https://stackoverflow.com/users/6143908/lancelot-lovejoy

I'm asking this question again because I do not have any points to comment on the original post, however, after spending 2 days on this I thought it was important to put this here: Lancelot Lovejoy had it bang on, the order matters. wherever you're defining your app object...

var app = builder.Build();
app.UseAuthentication(); // <-- first
app.UseAuthorization(); // <-- second

I don't know why the order matters, maybe someone can explain it to me, but I seriously lost 2 freaking days because of it. Hopefully, this will save someone that same time. Thank you a million times over Lancelot.

  • That’s the order of things happening. If you try to authorize without first authenticating it won’t work. These are middleware components and will run in the order introduced so order matters – Sami Kuhmonen Sep 28 '22 at 09:02

1 Answers1

3

First you always have to authentication to know who the user is. After that you do authorization to figure out if the user is authorized to access a given resource or not.

You can't determine what a user is allowed to do, if you don't know who it is. authentication is all about who is the user?

Just like my diagram here: enter image description here

Here's a good video about it: Implementing Authorization in Web Applications and APIs - Brock Allen & Dominick Baier

To help you about your token problem, then look in the logs, or perhaps also post more about how you have configured JwtBearer.

Tore Nestenius
  • 16,431
  • 5
  • 30
  • 40