問題描述
我將令牌作為字符串傳遞給 SOAP 服務,并已驗證該令牌有效.我現在有一個 SecurityToken,在調試模式下我可以看到所有聲明,特別是我想傳遞給另一個方法的 userId 聲明.我似乎無法弄清楚如何獲得索賠.現在我解碼了令牌的字符串版本(令牌的未經驗證的字符串版本,我至少等到成功驗證之后.)這是代碼塊:
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);
}
如何從 SecurityToken 中獲取聲明?
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.
推薦答案
我剛剛也遇到了同樣的情況,就是在調試的時候,SecurityToken 上可以看到 Payload 屬性,但是在編輯代碼的時候好像沒有 Payload 屬性.
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.
看起來SecurityToken的底層類型是JwtSecurityToken(盡管securityCode.GetType()的QuickWatch返回SecurityToken,而不是JwtSecurityToken.).無論如何,轉換為實際的底層類型并引用 Payload 集合對我來說是訣竅.
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.
一種解決方案:
string userId = ((JwtSecurityToken)access_token).Payload["userId"].ToString();
這篇關于如何從經過身份驗證的 SecurityToken 中獲取聲明的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!