c# User.IsInRole fails on unit test

r3plica

I have this method:

[HttpPut]
[AuthorizeClaim("field:write")]
[ApiConventionMethod(typeof(AttemptApiConventions), nameof(AttemptApiConventions.AttemptPut))]
public override async Task<ActionResult<Field>> UpdateAsync(Field model)
{
    var getAttempt = await Mediator.Send(new GenericGet<Field>(model.Id));
    if (getAttempt.Failure) return Ok(getAttempt);
    
    var field = getAttempt.Result;
    
    if (!field.IsSpecification && !User.IsInRole("Administrator"))
        return Ok(new ForbiddenError(string.Format(Resources.PermissionError, "this field")).ToAttempt<Field>());

    if (!field.IsSpecification && model.Name != field.Name)
        return Ok(new ValidationError(string.Format(Resources.CannotBeChanged, nameof(Field.Name))).ToAttempt<Field>());

    return await base.UpdateAsync(model);
}

As you can see, I check if the User.IsInRole to display a different error message when they are trying to change a field. The problem is, I have this unit test:

[Test]
public async Task ReturnBadRequestIfSpecificationFieldNameChanges()
{
    // Assemble
    var model = new Field {Id = 1, IsSpecification = false, Name = "Test"};
    var services = FieldsControllerContext.GivenServices();
    var controller = services.WhenCreateController("Administrator");

    services.Mediator.Send(Arg.Any<GenericGet<Field>>())
        .Returns(new Field {Id = 1, IsSpecification = false, Name = "Old"});

    // Act
    var actionResult = await controller.UpdateAsync(model);

    // Assert
    actionResult.ShouldBeBadRequest(string.Format(Sxp.Web.Properties.Resources.CannotBeChanged, nameof(Field.Name)));
}

Take a look at the line services.WhenCreateController("Administrator");. It is passing the role I want the mocked user to be a member of. This is set like this:

public static class ControllerExtensions
{
    public static T WithUser<T>(this T controller, string roles = null) where T: ControllerBase
    {
        var id = Guid.NewGuid().ToString();
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, "example name"),
            new Claim(ClaimTypes.NameIdentifier, id),
            new Claim(JwtClaimTypes.Subject, id),
        };

        if (!string.IsNullOrEmpty(roles))
        {
            var r = roles.Split(",");

            claims.AddRange(r.Select(role => new Claim(JwtClaimTypes.Role, role)));
        }

        var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "mock"));

        controller.ControllerContext = new ControllerContext
        {
            HttpContext = new DefaultHttpContext
            {
                User = user
            }
        };

        return controller;
    }
}

When I debug my test, I can see this:

enter image description here

Can anyone tell me why?

r3plica

I found the answer. This line was to blame:

claims.AddRange(r.Select(role => new Claim(JwtClaimTypes.Role, role)));

It isn't JwtClaimTypes that it checks, it actually checks for:

"http://schemas.microsoft.com/ws/2008/06/identity/claims/role"

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related