Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the claims out of a authenticated SecurityToken

I'm passing a token as a string into a SOAP service and have validated that the token is valid. I now have a SecurityToken that in debug mode I can see all the claims and specifically the userId claim I'd like to pass into another method. I can't seem to figure out how to get at the claims. For now I decoded the string version of the token (the none validated string version of the token, I at least waited until after a successful validation.) Here is that code block:

SecurityToken validatedToken = null;

if (VerifyToken(sPassword, ref response, ref validatedToken))
{
    var claimsObj = JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(claims)));
    JToken userId = claimsObj.GetValue("userId");
    return implClass.Process(userId);
}

How do I get the claims out of a SecurityToken?

validatedToken.Id; // not it
validatedToken.ToClaimsPrincipal(cert); // doesn't work

Nothing else seemed promising to me as far as exposed properties, but since I can see the claims in the debugger I'm sure there is a way that I'm just not seeing.

like image 576
user2197446 Avatar asked Aug 26 '16 20:08

user2197446


2 Answers

I just experienced the same thing, namely that while debugging, a Payload property is visible on the SecurityToken but there appears to be no Payload property when editing the code.

It looks like the underlying type of the SecurityToken is JwtSecurityToken (despite the QuickWatch of securityCode.GetType() returning SecurityToken, rather than JwtSecurityToken.). Anyway, casting to the actual underlying type and referencing the Payload collection did the trick for me.

One solution:

string userId = ((JwtSecurityToken)access_token).Payload["userId"].ToString();
like image 153
Eric McLachlan Avatar answered Sep 18 '22 15:09

Eric McLachlan


Likely you are seeing the claims because the debugger is using the real type of the object, not the base SecurityToken class. Cast it as the real type, and you should have easier access to the claims.

That, or use a securityTokenHAndler to validate and retrieve out the claim collection.

https://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.validatetoken(v=vs.110).aspx

like image 38
Tim Avatar answered Sep 17 '22 15:09

Tim