Skip to content

Instantly share code, notes, and snippets.

@jwcarroll
Created January 31, 2012 04:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jwcarroll/1708922 to your computer and use it in GitHub Desktop.
Save jwcarroll/1708922 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,
WhiteList,
BlackList
}
public class MockPrincipal: IPrincipal, IIdentity
{
private HashSet<String> Roles { get; 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";
}
public void AddRoles(params String[] roles)
{
Behavior = MockPrincipalBehavior.WhiteList;
if (roles == null || roles.Length == 0) return;
var rolesToAdd = roles.Where(r => !Roles.Contains(r));
foreach (var role in rolesToAdd)
Roles.Add(role);
}
public void IgnoreRoles(params String[] roles)
{
Behavior = MockPrincipalBehavior.BlackList;
AddRoles(roles);
}
public void RemoveRoles(params String[] roles)
{
if (roles == null || roles.Length == 0) return;
var rolesToAdd = roles.Where(r => Roles.Contains(r));
foreach (var role in rolesToAdd)
Roles.Remove(role);
}
public void RemoveAllRoles()
{
Roles.Clear();
}
#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
}
}
@Broda
Copy link

Broda commented Oct 17, 2013

Exactly what I was looking for, thanks!

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