Skip to content

Instantly share code, notes, and snippets.

@leftler
Forked from jwcarroll/MockPrincipal.cs
Created December 10, 2012 16:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leftler/4251707 to your computer and use it in GitHub Desktop.
Save leftler/4251707 to your computer and use it in GitHub Desktop.
Mock IPrincipal / IIdentity object that can be used for unit testing security.
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
}
}
@leftler
Copy link
Author

leftler commented Dec 10, 2012

There where 3 chages done to the code.

  1. AddRoles, IgnoreRoles, RemoveRoles, RemoveAllRoles where unneeded and removed by making Roles's get publicly visible.
  2. behavior was never assigned to Behavior in the constuctor
  3. Added some comments toMockPrincipalBehavior

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment