Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Claims while testing controller in asp.net core

Working in asp.net core, there are several controllers which has claims. The sample code is like this.

[HttpGet, Route("GetCustomerList")]
        public ActionResult<GenericResponse> Get()
        {
            var claims = User as ClaimsPrincipal;
            string username = claims.Claims.Where(c => c.Type == "UserName").Select(x => x.Value).FirstOrDefault();
            string roleid = claims.Claims.Where(c => c.Type == "RoleId").Select(x => x.Value).FirstOrDefault();
            ........
            ........
        }

How should I handle this claims while controller testing? I have tried the solution given How to add claims in a mock ClaimsPrincipal i.e. first solution. However, in my controller while debugging gives User a null and it stops.

like image 412
Ian Avatar asked Sep 03 '25 06:09

Ian


1 Answers

The User you are trying to access in your controller is found on the HttpContext so you can create a DefaultHttpContext for the controller under test and link a ClaimsPrincipal to this DefaultHttpContext as per the example below:

var fakeClaims = new List<Claim>()
{
   new Claim(ClaimTypes.Name, "name"),
   new Claim("RoleId", "1"),
   new Claim("UserName", "John")
};

var fakeIdentity = new ClaimsIdentity(fakeClaims, "TestAuthType");
var fakeClaimsPrincipal = new ClaimsPrincipal(fakeIdentity);

ControllerToTest controller = new ControllerToTest();

ControllerToTest.ControllerContext.HttpContext = new DefaultHttpContext
{
   User = fakeClaimsPrincipal 
};

ControllerToTest.Get();

You can also mock the HttpContext as per this example

like image 101
majita Avatar answered Sep 04 '25 19:09

majita