-
-
Save leftler/4251707 to your computer and use it in GitHub Desktop.
Mock IPrincipal / IIdentity object that can be used for unit testing security.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Security.Principal; | |
namespace TechnoFattie.Lib.Tests.Mocks | |
{ | |
public enum MockPrincipalBehavior | |
{ | |
AlwaysReturnTrue, | |
/// <summary> | |
/// This is how a normal principal operates. If the role is in the list, then | |
/// you get access. | |
/// </summary> | |
WhiteList, | |
/// <summary> | |
/// This works opposite to a normal principal. If the role is in the list, then | |
/// you get denied access. | |
/// This is useful for when there are multiple roles needed to perform an action | |
/// (think nested calls), and you want to see how your code behaves when the | |
/// user doesn't have one of them. | |
/// </summary> | |
BlackList | |
} | |
public class MockPrincipal : IPrincipal, IIdentity | |
{ | |
public HashSet<String> Roles { get; private set; } | |
public MockPrincipalBehavior Behavior { get; set; } | |
public MockPrincipal(String name = "TestUser", MockPrincipalBehavior behavior = MockPrincipalBehavior.AlwaysReturnTrue) | |
{ | |
Roles = new HashSet<String>(); | |
Name = name; | |
IsAuthenticated = true; | |
AuthenticationType = "FakeAuthentication"; | |
Behavior = behavior; | |
} | |
#region IPrincipal Members | |
public IIdentity Identity { get { return this; } } | |
public bool IsInRole(string role) | |
{ | |
if (Behavior == MockPrincipalBehavior.AlwaysReturnTrue) | |
return true; | |
var isInlist = Roles.Contains(role); | |
if (Behavior == MockPrincipalBehavior.BlackList) | |
return !isInlist; | |
return isInlist; | |
} | |
#endregion | |
#region IIdentity Members | |
public string AuthenticationType { get; set; } | |
public bool IsAuthenticated { get; set; } | |
public string Name { get; set; } | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There where 3 chages done to the code.
AddRoles
,IgnoreRoles
,RemoveRoles
,RemoveAllRoles
where unneeded and removed by makingRoles
'sget
publicly visible.behavior
was never assigned toBehavior
in the constuctorMockPrincipalBehavior