//set some claims first
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name,"test name"),
new Claim("Token","token123"),
new Claim("Number","3")
//new Claim("dummy","dummy string")
};
var ci = new ClaimsIdentity(claims);
//most seen way, throw error if not exists
var name = ci.Claims.First(x => x.Type == ClaimTypes.Name).Value;
var token = ci.Claims.First(x => x.Type == "Token").Value;
//using FirstOrDefault() only, throw error if not exists
//var dunno = ci.Claims.FirstOrDefault(x => x.Type == "dunno").Value;
Using this way is easy, but if the claim not exists, if will cause error, whatever you are using First() or FirstOrDefault(). If want to using FirstOrDefault() to get claim value, you can using this fixed way.
//fixed FirstOrDefault way: return null if not exists
var dunno = ci.Claims.Where(x => x.Type == "dunno").Select(x => x.Value).FirstOrDefault();
but you can use HasClaim method to check claim exist first, and give a proper value if it not exists.
//safe way: using HasClaim to check
var dummy = ci.HasClaim(x => x.Type == "dummy")
? ci.Claims.First(x => x.Type == "dummy").Value
: null;
or you can choose this short way by using FindFirst method.
//short way: using FindFirst
var dummyShort = ci.FindFirst("dummy")?.Value;
//short way for int
int.TryParse(ci.FindFirst("Number")?.Value, out var number);
I think use ClaimsIdentity.FindFirst Method is the best practices for get claim value.
You can test those here in here
No comments:
Post a Comment