-
Notifications
You must be signed in to change notification settings - Fork 36
Mocking the Authorization Provider
sergeyshushlyapin edited this page Nov 4, 2014
·
1 revision
[Fact]
public void HowToMockAuthorizationProvider()
{
// create sample user
var user = Sitecore.Security.Accounts.User.FromName(@"extranet\John", true);
using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db
{
new Sitecore.FakeDb.DbItem("home")
})
{
Sitecore.Data.Items.Item home = db.GetItem("/sitecore/content/home");
// configure authorization provider mock to deny item read for the user
var provider =
Substitute.For<Sitecore.Security.AccessControl.AuthorizationProvider>();
provider
.GetAccess(home, user, Sitecore.Security.AccessControl.AccessRight.ItemRead)
.Returns(new Sitecore.FakeDb.Security.AccessControl.DenyAccessResult());
// switch the authorization provider
using (new Sitecore.FakeDb.Security.AccessControl.AuthorizationSwitcher(provider))
{
// check the user cannot read the item
bool canRead =
Sitecore.Security.AccessControl.AuthorizationManager.IsAllowed(
home,
Sitecore.Security.AccessControl.AccessRight.ItemRead,
user);
Xunit.Assert.False(canRead);
}
}
}
[Fact]
public void HowToUnitTestItemSecurityWithMockedProvider()
{
// create sample item
using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db
{
new Sitecore.FakeDb.DbItem("home")
})
{
Sitecore.Data.Items.Item home = db.GetItem("/sitecore/content/home");
// substitute the authorization provider
var provider =
Substitute.For<Sitecore.Security.AccessControl.AuthorizationProvider>();
using (new Sitecore.FakeDb.Security.AccessControl.AuthorizationSwitcher(provider))
{
// call your business logic that changes the item security, e.g. denies Read
// for Editors
var account = Sitecore.Security.Accounts.Role.FromName(@"sitecore\Editors");
var accessRight = Sitecore.Security.AccessControl.AccessRight.ItemRead;
var propagationType = Sitecore.Security.AccessControl.PropagationType.Entity;
var permission = Sitecore.Security.AccessControl.AccessPermission.Deny;
Sitecore.Security.AccessControl.AccessRuleCollection rules =
new Sitecore.Security.AccessControl.AccessRuleCollection
{
Sitecore.Security.AccessControl.AccessRule.Create
(account, accessRight, propagationType, permission)
};
Sitecore.Security.AccessControl.AuthorizationManager.SetAccessRules(home, rules);
// check the provider is called with proper arguments
provider
.Received()
.SetAccessRules(
home,
NSubstitute.Arg.Is<Sitecore.Security.AccessControl.AccessRuleCollection>(
r => r[0].Account.Name == @"sitecore\Editors"
&& r[0].AccessRight.Name == "item:read"
&& r[0].PropagationType.ToString() == "Entity"
&& r[0].SecurityPermission.ToString() == "DenyAccess"));
}
}
}