Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

userManager.FindByName does not return roles

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
like image 744
Makla Avatar asked Feb 13 '17 07:02

Makla


1 Answers

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);.

like image 119
Kévin Chalet Avatar answered Oct 20 '22 21:10

Kévin Chalet