I am using OpenIddict for token authentication. Yesterday when I call userManager.FindByNameAsync(request.Username)
I get User with Roles.
Today I get user with Roles property count = 0.
I tried to load roles with await userManager.GetRolesAsync(user);
and I get array with count 3. That means user has roles.
I do not know what changed, but how can I load user with roles with FindByNameAsync function?
Complete code:
[HttpPost("token"), Produces("application/json")]
public async Task<IActionResult> Exchange(OpenIdConnectRequest request)
{
Debug.Assert(request.IsTokenRequest(),
"The OpenIddict binder for ASP.NET Core MVC is not registered. " +
"Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");
if (request.IsPasswordGrantType())
{
var user = await userManager.FindByNameAsync(request.Username); //roles count is 0
if (user == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidGrant,
ErrorDescription = "The email/password couple is invalid."
});
}
var roles = await userManager.GetRolesAsync(user); //roles count is 3
but how can I load user with roles with FindByNameAsync function?
You can't (at least not without implementing your own IUserStore
).
Under the hood, the default ASP.NET Core Identity store implementation (based on EF) doesn't eagerly load the navigation properties associated with the user entity for performance reasons, which is why the Roles
property is not populated.
To load the roles associated with a user, use UserManager.GetRolesAsync(user);
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With