I followed the documentation here and was able to get my controllers working with the [Authorize]
header. I am using IdentityServer with ASP.NET Identity as my user store.
In my ConfigureServices
I have:
services.AddIdentity<KipUser, IdentityRole>()
.AddEntityFrameworkStores<KipDbContext>()
.AddDefaultTokenProviders();
In my Configure
I have:
app.UseIdentityServer();
app.UseAuthorization();
And in my controller I have done a few tests:
[Authorize]
public IEnumerable<MyDTO> GetData(int count = 3) {
var test = User; // The User.Identity.Name is empty for some reason
var id = User.FindFirst(ClaimTypes.NameIdentifier).Value; // Successfully gets the Guid
var test2 = _userManager.GetUserAsync(User); // result is null
var test3 = _userManager.GetUserId(User); //returns null
var test4 = _userManager.FindByIdAsync(id); // Successfully gets the User from the DB
It seems there is a misconfiguration because the UserManager fails to get the ASP.Net Identity from the ClaimsPrincipal User
variable. Am I assuming too much that the .AddEntityFrameworkStores<KipDbContext>()
would configure the application to know how to _userManager.GetUserAsync(User)
instead of me needing to search for the claim myself with this _userManager.FindByIdAsync(User.FindFirst(ClaimTypes.NameIdentifier).Value)
?
The main reason I asked this question is because I saw lots of information about this for IdentityServer 2 and 3 that seemed related. I couldn't get those fixes to work in my IdentityServer 4 project so I thought it was a different issue. It is the same issue. As @Tore pointed out, it's an issue with the claims, but I assumed that this would be taken care of with app.UseIdentityServer();
This describes the issue clearly:
UseIdentity and UserManager disagree on where the user ID claim is stored
Even though we are calling app.UseIdentityServer();
it seems there are some default mappings put in by Microsoft that need to be cleared out.
Per that issue, adding JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
in the Startup.cs
Configure
function before app.UseIdentityServer();
fixed the problem for me. I can now see the claims are unchanged in the controller, and both _userManager.GetUserAsync(User);
and _userManager.GetUserId(User);
work as expected.
Surprisingly, this function call is not included in the IdentityServerAspNetIdentity
sample project.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments