How to get the claims out of a authenticated Secur

2020-06-23 05:45发布

问题:

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.

回答1:

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();


回答2:

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