Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you test your ASP MVC apps for user based security?

I've been writing tests for my domain objects for some time now, but I'm still not quite sure how to go about testing for security in my web project. Certain users in certain environments can access certain properties of my models etc, but how would you go about testing this? Right now, I'm basing it on the current authenticated user, but how would I go about injecting a fake authentication provider?

This is probably a dumb question, but if anyone can help me get out of the testing dark ages, it would be much appreciated.

like image 871
Scott Holden Avatar asked Jan 30 '09 17:01

Scott Holden


People also ask

What is security MVC?

MVC provides a lot of infrastructure support for Forms Authentication. Forms authentication is highly customizable, you can customize everything from the sign in form, to where the credentials are stored and how those credentials are validated. Forms Authentication in ASP.NET relies on cookies by default.


1 Answers

That link is ONE way, but it's nicer to use a Mock:

    Mock<ControllerContext> MockContext(string userName)
    {
        var mockContext = new Mock<ControllerContext>();
        // mock an authenticated user
        mockContext.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);
        mockContext.SetupGet(p => p.HttpContext.User.Identity.IsAuthenticated).Returns(true);
        return mockContext;
    }

    [TestMethod]
    public void DinnersController_Delete_Should_Fail_With_InvalidOwner_Given_Wrong_User()
    {
        //set by default
        var mockContext = MockContext("scottha");

        // mock an authenticated user
        _dinnerController.ControllerContext = mockContext.Object;

        ViewResult result = _dinnerController.Delete(1, "") as ViewResult;
        Assert.AreEqual("InvalidOwner", result.ViewName);
    }
like image 116
Scott Hanselman Avatar answered Nov 06 '22 21:11

Scott Hanselman