fluent security unit testing

377 Views Asked by At

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?

2

There are 2 best solutions below

1
Kristoffer Ahl On BEST ANSWER

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

1
Renu On

Though I got this working but found a severe limitation to Fluent Security. It is not able to differentiate between the two action methods with same name !!

e.g.

public ActionResult Edit(int id){}

and

[HttpPost]
public ActionResult Edit(SomeCommand command){}

if I want to give access to Guest on Edit (Get) and Edit (Post) to Admin User, I cannot do it via Fluent Security as it identifies both the methods as one. I will not recommend this library as this is a severe limitation!