openiddict-test icon indicating copy to clipboard operation
openiddict-test copied to clipboard

Empty Roles

Open jaredcnance opened this issue 8 years ago • 4 comments

For some reason User.Roles is empty when it reaches the controller and throws a 403 for role based authorization.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IDatabaseInitializer databaseInitializer, UserManager<ApplicationUser> userManager)
{
...
app.UseOpenIddictCore(...);
app.UseJwtBearerAuthentication(new JwtBearerOptions() {...});
app.Use(async (context, next) =>
      {
        var user = await userManager.GetUserAsync(context.User);
//-------> user.Roles.Count = 1
        await next.Invoke();
      });
app.UseMvc(...);
...
}

But, in the controller:

[Authorize]
  public class MeController : Controller
  {
    private CoreModelsDbContext _context;
    private readonly UserManager<ApplicationUser> _userManager;

    public MeController(CoreModelsDbContext context, UserManager<ApplicationUser> userManager)
    {
      _context = context;
      _userManager = userManager;
    }

    [Route("api/v1/me"), HttpGet]
    public async Task<IActionResult> Get()
    {
      var user = await _userManager.GetUserAsync(User);
//-------> user.Roles.Count = 0
      return user == null ? Ok("No user / not logged in") : Ok(user);
    }
  }

Any idea how this would happen?

jaredcnance avatar May 31 '16 17:05 jaredcnance

I've got the same issue. Any hint regarding "permission denied 403" error is highly appreciated. With the same controller role based authentication works fine using cookie authentication.

Update: Ah I am sorry, I just found out. I missed the scope "roles" in my json payload! Now everything is working. @jaredcnance btw: the roles property is empty because there is no support for lazy loading in ef7 as of yet. You need to load the roles explicitly:

var user = await _userManager.GetUserAsync(User);
var roles = await _userManager.GetRolesAsync(user);

return Ok(new { User = user, Roles = roles});

snowping avatar Jun 07 '16 21:06 snowping

Hi @snowping , you can explain me where the change is made. I am noob. Thank you.

DidierVanegas avatar Jun 30 '16 18:06 DidierVanegas

@DidierVanegas sure, in order to get a proper token (including roles) you need to send x-www-form-urlencoded params to a URL e.g. http://localhost:5000/connect/token. Enclosed you'll find a postman example how to generate a token including "roles" in scope parameter.

image

Hope it'll work out.

snowping avatar Jul 02 '16 07:07 snowping

@snowping thank you very much, it works now!

DidierVanegas avatar Jul 05 '16 19:07 DidierVanegas