-1

I have to get roles of a user from DB as per my application nature. I am authenticating user in context.AcquireRequestState += context_AcquireRequestState; event handler in HttpModule. Can I do db calls from HttpModule to assign roles in Identity? Is it good practice? if not, where I have to do it before controller’s action method called.?

deen
  • 467
  • 2
  • 4
  • 10
  • We've done that before but in a HttpHandler using windows authentication and updating the claims. Yes you can make DB calls within a HttpModule and HttpHandler, but within a module you will need to handle caching and refreshing of tokens. I wouldn't recommend putting authentication in a module unless you're making a call every time to check whether the token is valid. I would use IdentityServer for the handling your scenario. – Rav Jun 26 '19 at 10:55

1 Answers1

0

I dont know what you doing with Aquaire request state, Ideally you have to do as below:

[Authorize(Roles="Admin")]
[Route("user/{id:guid}/roles")]
[HttpPut]
public async Task<IHttpActionResult> AssignRolesToUser([FromUri] string id, [FromBody] string[] rolesToAssign)
{

    var appUser = await this.AppUserManager.FindByIdAsync(id);

    if (appUser == null)
    {
        return NotFound();
    }

    var currentRoles = await this.AppUserManager.GetRolesAsync(appUser.Id);

    var rolesNotExists = rolesToAssign.Except(this.AppRoleManager.Roles.Select(x => x.Name)).ToArray();

    if (rolesNotExists.Count() > 0) {

        ModelState.AddModelError("", string.Format("Roles '{0}' does not exixts in the system", string.Join(",", rolesNotExists)));
        return BadRequest(ModelState);
    }

    IdentityResult removeResult = await this.AppUserManager.RemoveFromRolesAsync(appUser.Id, currentRoles.ToArray());

    if (!removeResult.Succeeded)
    {
        ModelState.AddModelError("", "Failed to remove user roles");
        return BadRequest(ModelState);
    }

    IdentityResult addResult = await this.AppUserManager.AddToRolesAsync(appUser.Id, rolesToAssign);

    if (!addResult.Succeeded)
    {
        ModelState.AddModelError("", "Failed to add user roles");
        return BadRequest(ModelState);
    }

    return Ok();
}

Source read here

SmartestVEGA
  • 8,415
  • 26
  • 86
  • 139
  • I have to get roles immediatelyafter authuntication done in HttpModel event. I am asking is it goot practice to do that in httpmodule using database call? – deen Jun 27 '19 at 04:24