1

I was able to implement the below JWT solution in my MVC WebApi following below link JWT Authentication for Asp.Net Web Api

Now, I want to access claim in the controllers, but all claims are null. I have tried a few things and all of them returns null.

How is claim added in JwtAuthenticationAttribute:

protected Task<IPrincipal> AuthenticateJwtToken(string token)
        {
            string username;

            if (ValidateToken(token, out username))
            {
                //Getting user department to add to claim.
                eTaskEntities _db = new eTaskEntities();
                var _user = (from u in _db.tblUsers join d in _db.tblDepartments on u.DepartmentID equals d.DepartmentID select u).FirstOrDefault();
                var department = _user.DepartmentID;

                // based on username to get more information from database in order to build local identity
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, username),
                    new Claim(ClaimTypes.SerialNumber, department.ToString())
                    // Add more claims if needed: Roles, ...
                };

                var identity = new ClaimsIdentity(claims, "Jwt");
                IPrincipal user = new ClaimsPrincipal(identity);

                return Task.FromResult(user);
            }

            return Task.FromResult<IPrincipal>(null);
        }

What I have tried so far

Extension method to get claim:

public static class IPrincipleExtension
{
    public static String GetDepartment(this IIdentity principal)
    {
        var identity = HttpContext.Current.User.Identity as ClaimsIdentity;
        if (identity != null)
        {
            return identity.FindFirst("SerialNumber").Value;
        }
        else
            return null;
    }
}

Using the function defined in the post (link above):

TokenManager.GetPrincipal(Request.Headers.Authorization.Parameter).FindFirst("SerialNumber")

Trying to access Claim through thread:

((ClaimsPrincipal)System.Threading.Thread.CurrentPrincipal.Identity).FindFirst("SerialNumber")

For all the above, a claim is always null. What am I doing wrong?

Hitin
  • 442
  • 7
  • 21

1 Answers1

1

You should try this to get your claim:

if (HttpContext.User.Identity is System.Security.Claims.ClaimsIdentity identity)
{                   
    var serialNum = identity.FindFirst(System.Security.Claims.ClaimTypes.SerialNumber).Value;
}

I reserve the identity.FindFirst("string_here").Value for when I set my claims like this:

var usersClaims = new[]
{               
    new Claim("string_here", "value_of_string", ClaimValueTypes.String),
    ...
};

rather than using "prebuilt" values like this:

var usersClaims = new[]
{               
    new Claim(ClaimTypes.Name, "value_of_name", ClaimValueTypes.String),
    ...
};
thalacker
  • 2,389
  • 3
  • 23
  • 44