Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing claimsPrincipal after changing roles

I'm having some issues with changing role in dotnetcore identity.

I have the following code.

private async Task SetRoleToX(ClaimsPrincipal claimsPrincipal, string X)
{
    var currentUser = await UserManager.GetUserAsync(claimsPrincipal);
    var roles = await UserManager.GetRolesAsync(currentUser);

    await UserManager.RemoveFromRolesAsync(currentUser, roles);
    await UserManager.AddToRoleAsync(currentUser, X);
    await SignInManager.RefreshSignInAsync(currentUser);
}

I cannot get the ClaimsPrincipal to update.

I have tried using sign in and sign out.

The role switch works fine if I manually sign in and out.

I have been searching the web and alot of people say this should work :(

like image 934
Spaceman Avatar asked Feb 01 '17 09:02

Spaceman


1 Answers

Rather annoyingly all I had to do was send the token back with the request.

I cant believe i didn't think of it hope this helps someone.

Update with some code as requested

// In controller

public async Task SwapRole([FromBody]RoleSwapRequestDto dto)
{
    await _service.SwapRole(
        User,
        dto.RoleName
    );

    return await AddCookieToResponse();
}

private async Task AddCookieToResponse()
{
    // Make your token however your app does this (generic dotnet core stuff.)
    var response = await _tokenService.RegenToken(User);

    if (response.Data != null && response.Data.Authenticated && response.Data.TokenExpires.HasValue)
    {
        Response.Cookies.Append(AuthToken, response.Data.Token, new CookieOptions
        {
            HttpOnly = false,
            Expires = response.Data.TokenExpires.Value
        });
    }

    return response;
}

/// inside _service
public async Task SwapRole(ClaimsPrincipal claimsPrincipal, string X)
{
    var currentUser = await UserManager.GetUserAsync(claimsPrincipal);
    var roles = await UserManager.GetRolesAsync(currentUser);

    await UserManager.RemoveFromRolesAsync(currentUser, roles);
    await UserManager.AddToRoleAsync(currentUser, X);
    await SignInManager.RefreshSignInAsync(currentUser);
}
like image 113
Spaceman Avatar answered Nov 20 '22 13:11

Spaceman