如何测试ASP MVC应用程序以获得基于用户的安全性?

时间:2009-01-30 17:22:43

标签: asp.net-mvc authentication testing

我已经为我的域对象编写了一段时间的测试,但我仍然不太确定如何在我的web项目中测试安全性。某些环境中的某些用户可以访问我的模型的某些属性等,但您将如何进行测试呢?现在,我将它基于当前经过身份验证的用户,但我将如何注入假身份验证提供程序?

这可能是一个愚蠢的问题,但如果有人能帮我摆脱测试的黑暗时代,那将非常感激。

3 个答案:

答案 0 :(得分:8)

这个链接是单向的,但使用模拟更好:

    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);
    }

答案 1 :(得分:0)

如果使用TDD,您的测试应该只测试有问题的代码,所有其他相关对象应该是模拟/伪造

除此之外,您还需要一个模拟安全提供程序,它可以模拟您需要测试的用户案例(guest,user1,user2,admin等)

当您使用当前的MVC RC创建一个空白的MVC项目时,您将获得一个带有模拟安全提供程序(成员资格/角色等)的基本测试框架。他们需要一些充实,但提供基本设计

答案 2 :(得分:0)

还有第三个选项,即使用Xania.AspNet.Simulator

首先准备控制器动作

// arrange
var controllerAction = new AccountController().Action(c => c.ChangePassword())
    .Authenticate(<username>, <roles>);

接下来,根据您的实施情况,您有两种选择,

第一种情况,如果你返回一个HttpUnauthorizedResult,即当你使用Authorize属性时或者当你覆盖你的控制器的AuthorizeCore时,你可以像下面那样测试它,在这种情况下不会调用实际的action方法。

// act, assert
controllerAction.Authorize().Should().BeNull();

第二种情况是您实际在操作方法中验证用户:

// act
var result = controllerAction.Execute();
// assert
result.ActionResult.Should().NotBeOfType<HttpUnauthorizedResult>();