I am implementing role-based authentication using ASP.NET Identity. I have issue with assign roles

Hello guys, I am implementing role-based authentication using ASP.NET Identity. I have already added three roles: Member, Admin (can create resources), and Owner (can assign roles, grant or revoke the Admin role). I want to keep my controllers clean and move the logic to the infrastructure layer, but something feels wrong. I can't write proper code to prevent the Owner from demoting themselves. Any ideas?
cs
public sealed record AssignAdminRoleRequest
{
public required string Email { get; set; }
}

public async Task<TokensResponse> AssignAdminRole(AssignAdminRoleRequest request)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user is null)
{
throw new AuthenticationException();
}
if (!user.EmailConfirmed)
throw new AuthenticationException($"User :{request.Email} needs to confirm email");

if (await _userManager.IsInRoleAsync(user, "Admin"))
{
throw new IdentityException("User already has this role");
}


var result = await _userManager.AddToRoleAsync(user, "Admin");
if (!result.Succeeded)
throw new IdentityException("Failed to add Role. Try again later");

return await CreateTokenResponce(user);
}
cs
public sealed record AssignAdminRoleRequest
{
public required string Email { get; set; }
}

public async Task<TokensResponse> AssignAdminRole(AssignAdminRoleRequest request)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user is null)
{
throw new AuthenticationException();
}
if (!user.EmailConfirmed)
throw new AuthenticationException($"User :{request.Email} needs to confirm email");

if (await _userManager.IsInRoleAsync(user, "Admin"))
{
throw new IdentityException("User already has this role");
}


var result = await _userManager.AddToRoleAsync(user, "Admin");
if (!result.Succeeded)
throw new IdentityException("Failed to add Role. Try again later");

return await CreateTokenResponce(user);
}
3 Replies
this_is_pain
this_is_pain3w ago
owner would be able to remove permissions from himself, but also to add them back
ВВассралман
if owner removes own permissions there is no owner anymore
this_is_pain
this_is_pain2w ago
not exactly, owner still can assign those permission to himself

Did you find this page helpful?