An unhandled exception occurred while processing the request in OpenIddict
The error you're seeing is caused by the fact your ClaimsPrincipal
doesn't have the mandatory sub
claim, as indicated by the exception message.
To fix that, you have two options: manually adding the sub
claim or asking Identity to use sub
as the name identifier claim.
Add the sub
claims to the principal returned by await _signInManager.CreateUserPrincipalAsync(user);
...
// Note: while ASP.NET Core Identity uses the legacy WS-Federation claims (exposed by the ClaimTypes class),
// OpenIddict uses the newer JWT claims defined by the OpenID Connect specification. To ensure the mandatory
// subject claim is correctly populated (and avoid an InvalidOperationException), it's manually added here.
if (string.IsNullOrEmpty(principal.FindFirstValue(OpenIdConnectConstants.Claims.Subject)))
{
identity.AddClaim(new Claim(OpenIdConnectConstants.Claims.Subject, await _userManager.GetUserIdAsync(user)));
}
... or ask Identity to use sub
as the name identifier claim:
services.Configure<IdentityOptions>(options =>
{
options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
});