1

I have a Custom UserPrincipal and I have an User Entity.

The User Entity holds a collection of Permissions.

I want to make my UserPrincipal aware of those Permissions and all I want to do is to inject the IPrincipal in the construtors I need and then call the IsInRole() method.

How do I achieve that with AutoFac? I'm not finding any reference of how to make the UserPrincipal aware of the User Entity. I could solve that by addidng the permissions to Claims and then get those claims in the IsInRole, but I don't know if that is a good idea?

EDIT:

After some tests I got to this solution:

public interface IUserPrincipal : IPrincipal
{
    Guid Id { get; }

    Guid? BossId { get; }

    string DisplayName { get; }

    string Email { get; }

    List<string> Permissions { get; }
}

public class UserPrincipal : IUserPrincipal
{
    private readonly User _user;

    public UserPrincipal(User user, IIdentity identity)
    {
        _user = user;
        Identity = identity;
    }

    public bool IsInRole(string role)
    {
        return Permissions.Contains(role);
    }

    public IIdentity Identity { get; }

    public Guid Id => _user.Id;

    public Guid? BossId => _user.BossId;

    public string DisplayName => _user.Name;

    public string Email => _user.Name;

    public List<string> Permissions
    {
        get
        {
            return _user.Permissions.Select(p => p.Name).ToList();
        }
    }
}

public User GetCurrentUser()
{
    var user = GetUserByEmail(emailAddress);

    if (user == null)
    {
        using (var unitOfWork = _unitOfWorkFactory.CreateUnitOfWork())
        {
            user = CreateNewUser(unitOfWork, emailAddress, displayName);
        }
    }

    Thread.CurrentPrincipal = new UserPrincipal(user, Thread.CurrentPrincipal.Identity);

    return user;
}

And then with AutoFac:

builder.Register(c => new UserPrincipal(c.Resolve<IUserService>().GetCurrentUser(), Thread.CurrentPrincipal.Identity)).As<IPrincipal>().InstancePerRequest();
DAG
  • 2,460
  • 5
  • 33
  • 61
  • 1
    Did you checked this SO post(http://stackoverflow.com/questions/1064271/asp-net-mvc-set-custom-iidentity-or-iprincipal)? – Ramanagom Dec 21 '15 at 13:54
  • Brilliant. No, no samples with AutoFac tho, but I think that is a good step forward, it seems like I'm on the right path. I try to post the solution soon. – DAG Dec 21 '15 at 14:14

0 Answers0