I have a solution that has my web application, my REST API, and my Identity Server 4. All of which are now on .net 5. Locally everything works fine, but once I load everything up to the server, I get an error on Postman.
Setup - The API, and the IDP server are on separate sites.
What I Know - I know the IDP server works because I can get a token in Postman. I also know that the actual API works because when I remove the [Authorize] attribute from the controller I have, the call from Postman works fine.
The Problem - The problem that I have now is that when I put the [Authorize] attribute back in, I always get a 401 Unauthorized error for the API call. Below is the Startup file portion that sets up the authentication:
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://bob.com/API-IDP/";
options.ApiName = "BOBSAPI";
options.ApiSecret = "bobssecret";
});
I also know that the Configure portion, that the order of the Use***** is correct. I've also tried tweaking with the AppPool settings, in terms of "Load Profile", all based on things I've found while searching. I've gone to the Identity 4 website and followed those examples as best as I can. Oh, one more thing. The IDP database has a table for PersistedGrants. I do see a few records in that table, which I think means the authentication worked? But if the authentication worked, then why did the API call return a 401? Is there something I need to do on the controller besides the [Authorization] attribute? I've spent 3 days on this and I'm pulling my hair out. Please help!
I would look at the response headers of the response from the API and see if this header gives any clues to why you are not authorized:
For example:
HTTP/1.1 401 Unauthorized
Date: Sun, 02 Aug 2020 11:19:06 GMT
WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid"
You should also make sure this flag is set to True in the AddJwtBearer config:
//True if token validation errors should be returned to the caller.
options.IncludeErrorDetails = true;
You can use a tool like Fiddler to do that.
Then I would look at the ASP.NET Core logfile to determine why it does not accept your token.
To complement this answer, I wrote a blog post that goes into more detail about this topic: Troubleshooting JwtBearer authentication problems in ASP.NET Core