openiddict-test
openiddict-test copied to clipboard
Empty Roles
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?
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});
Hi @snowping , you can explain me where the change is made. I am noob. Thank you.
@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.
Hope it'll work out.
@snowping thank you very much, it works now!