Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend the ClaimsPrincipal and ClaimsIdentity classes in MVC-6

I've been trying to figure this thing out for a few days now, but have to turn to you guys (again).

As the title says, I would like to implement my custom ClaimsPrincipal and ClaimsIdentity, so that I can attach a few more properties to my Identity-instance.

I have done this earlier in MVC-5, using Global.asax.cs and an inherited BaseController. In MVC-6 it seems like startup.cs would be the entry point for this, but I can't figure it out.

These are my two classes:

public class BaseIdentity : ClaimsIdentity
{
    public Guid UserId { get; set; }
    public Guid OrgId { get; set; }
    public string OrgName { get; set; }

    public BaseIdentity()
    {
    }
}

And..

public class BasePrincipal : ClaimsPrincipal
{
    private readonly BaseIdentity _identity;

    public BasePrincipal(BaseIdentity identity)
    {
        _identity = identity;
    }

    public new BaseIdentity Identity
    {
        get { return _identity; }
    }
}

How can I use these classes, instead of the default, when creating / retrieving Auth cookie?

There is a method called IApplicationBuilder.UseClaimsTransformation() , but can't find any documentation on how to use it - if it's even for this scenario?

Help much appreciated at this point! :)

BTW: I would like to point out that I've asked a similar question a week ago, when I first encountered this challenge. I got an answer, but this is something that I really have to fix, to make my website usable on MVC-6.

like image 889
mikal Avatar asked Mar 15 '23 23:03

mikal


1 Answers

I've done this using extension methods instead of inheritance.

public static class PrincipalExtensions
{
    public static string GetEmployeeNumber(this ClaimsPrincipal claimsPrincipal)
    {
        return claimsPrincipal.FindFirstValue("EmployeeNumber");
    }
}
like image 184
Fred Avatar answered Apr 27 '23 09:04

Fred