Search code examples
asp.net-mvcunit-testingauthenticationauthorizationfluent-security

fluent security unit testing


I have been writing some tests on my Fluent Security configuration off late. Though I can write tests verifying if a controller action method has a particular policy applied e.g.

expectations.Expect<HomeController>(x=>x.Index()).Has<IgnorePolicy>();

However, what I am looking for is, if I can write role specific tests.

e.g If I have given Admin Role access only to Index() of HomeController, I want to test something like

expectations.Expect<HomeController>(x=>x.Index()).Has<RequireRolePolicy>().For("Admin");

I do not find any examples on net, or any extensions in FLuentSecurity.TestHelper that can help me do this. any thoughts?


Solution

  • The Has extension has an overload that takes a predicate:

    expectations.Expect<HomeController>(x => x.Index())
        .Has<RequireRolePolicy>(policy => policy.RolesRequired.Contains("Admin"));
    

    As you can see the RequireRolePolicy exposes a RolesRequired property that you can test against.

    If you find yourself doing a lot of checking for a particular set of roles I would recommend creating a custom policy and just check for that policy instead. There's an example of this (an AdministratorPolicy) in the sample application on github: https://github.com/kristofferahl/FluentSecurity/blob/master/FluentSecurity.SampleApplication/AdministratorPolicy.cs