Search code examples
.netasp.net-coreasp.net-core-mvc.net-core-rc2

Claims on signin in .NET Core RC2


I'm porting a .NET 4.6 version to .NET Core RC2 and wondering how to do following in .NET Core RC2.

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        userIdentity.AddClaim(new Claim("FullName", string.Format("{0} {1}", this.Firstname, this.Lastname)));
        userIdentity.AddClaim(new Claim("Organization", this.Organization.Name));
        userIdentity.AddClaim(new Claim("Role", manager.GetRoles(this.Id).FirstOrDefault()));
        userIdentity.AddClaim(new Claim("ProfileImage", this.ProfileImageUrl));
        // Add custom user claims here
        return userIdentity;
}

and then a extension method for Identity.

public static class IdentityExtensions
{
    public static string FullName(this IIdentity identity)
    {
        var claim = ((ClaimsIdentity)identity).FindFirst("FullName");
        // Test for null to avoid issues during local testing
        return (claim != null) ? claim.Value : string.Empty;
    }

    public static string Organization(this IIdentity identity)
    {
        var claim = ((ClaimsIdentity)identity).FindFirst("Organization");
        // Test for null to avoid issues during local testing
        return (claim != null) ? claim.Value : string.Empty;
    }

    public static string Role(this IIdentity identity)
    {
        var claim = ((ClaimsIdentity)identity).FindFirst("Role");
        // Test for null to avoid issues during local testing
        return (claim != null) ? claim.Value : string.Empty;
    }

    public static string ProfileImage(this IIdentity identity)
    {
        var claim = ((ClaimsIdentity)identity).FindFirst("ProfileImage");
        // Test for null to avoid issues during local testing
        return (claim != null) ? claim.Value : string.Empty;
    }
}

Which gives me the result of using User.Identity.ProfileImg(); etc..


Solution

  • Sorry for letting you guys wait!

    I solved this by doing the following when creating a user. As in my case when the user is created I create claims which are stored as a relation to the user. Then I keep these values updated through the whole process, which means each time someone changes the values they must be updated in the claims table aswell.

    var user1 = new ApplicationUser()
    {
        Firstname = "MyName",
        Lastname = "MyLastname",
        UserName = "[email protected]",
        Email = "[email protected]",
        EmailConfirmed = true,
        PhoneNumber = "000000000",
        OrganizationId = organization.Id,
        ProfileImageUrl = "user.jpg"
    };
    await userManager.CreateAsync(user1, "Qwerty1!");
    await userManager.AddToRoleAsync(user1, "SuperAdmin");
    
    var claims1 = new List<Claim> {
        new Claim("Email", user1.Email),
        new Claim("FullName", string.Format("{0} {1}", user1.Firstname, user1.Lastname)),
        new Claim("Organization", organization.Name),
        new Claim("Role", "SuperAdmin"),
        new Claim("ProfileImage", user1.ProfileImageUrl)
    };
    
    await userManager.AddClaimsAsync(user1, claims1);
    

    Last but not least I create the extension to get access to these for the current logged in user in views and controllers.

    using System.Security.Claims;
    using System.Security.Principal;
    
    namespace Core.Extensions
    {
        public static class IdentityExtension
        {
            public static string FullName(this IIdentity identity)
            {
                var claim = ((ClaimsIdentity)identity).FindFirst("FullName");
                return (claim != null) ? claim.Value : string.Empty;
            }
    
            public static string Organization(this IIdentity identity)
            {
                var claim = ((ClaimsIdentity)identity).FindFirst("Organization");
                return (claim != null) ? claim.Value : string.Empty;
            }
    
            public static string Role(this IIdentity identity)
            {
                var claim = ((ClaimsIdentity)identity).FindFirst("Role");
                return (claim != null) ? claim.Value : string.Empty;
            }
    
            public static string ProfileImage(this IIdentity identity)
            {
                var claim = ((ClaimsIdentity)identity).FindFirst("ProfileImage");
                return (claim != null) ? claim.Value : string.Empty;
            }
    
            public static string Email(this IIdentity identity)
            {
                var claim = ((ClaimsIdentity)identity).FindFirst("Email");
                return (claim != null) ? claim.Value : string.Empty;
            }
        }
    
    }
    

    Then I can use is like this in my view for example

    @using Microsoft.AspNetCore.Identity
    @using Core.Extensions
    @{
        ViewData["Title"] = "Overview";
    }
    <h4 class="mt-0 mb-5">Welcome back @User.Identity.FullName()</h4>