Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you stub User.Identity.GetUserId() in ASP MVC 5 (Microsoft.AspNet.Identity)

How do you stub User.Identity.GetUserId() in ASP MVC 5 (Microsoft.AspNet.Identity) for a unit test of a MVC5 Controller? GetUserId() is an extension, so I can't mock it directly. And I need to assign the Id before the test. It seems that you have to create a Claim and assign it to a GenericIdentity. But it seems like a lot to do for a unit test. Do you know of any alternatives?

like image 835
jgarza Avatar asked Dec 09 '13 15:12

jgarza


People also ask

How can we get logged in user details in asp net core?

You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);

How does identity work in asp net?

ASP.NET Identity is Microsoft's user management library for ASP.NET. It includes functionality such as password hashing, password validation, user storage, and claims management. It usually also comes with some basic authentication, bringing its own cookies and multi-factor authentication to the party.

Why would you use ASP net Identity?

ASP.NET Identity can be used with all ASP.NET frameworks, such as ASP.NET Web Forms , MVC, Web Pages, Web API etc.ASP.NET Identity has been developed with some major security features like Two-Factor Authentication, Account Lockout, and Account Confirmation etc.


1 Answers

Thank you very much for the idea. I am using NSubstitute. I don’t have neither Microsoft Fakes nor JustMock. So I ended stuffing claims directly to the GenericIdentity so I could control the value of the UserId:

string username = "username";
string userid = Guid.NewGuid().ToString("N"); //could be a constant

List<Claim> claims = new List<Claim>{
    new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", username), 
    new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userid)
};
var genericIdentity = new GenericIdentity("");
genericIdentity.AddClaims(claims);
var genericPrincipal = new GenericPrincipal(genericIdentity, new string[] { "Asegurado" });
controllerContext.HttpContext.User = genericPrincipal;
like image 170
jgarza Avatar answered May 03 '23 15:05

jgarza