如何从经过身份验证的 SecurityToken 中获取声明

How to get the claims out of a authenticated SecurityToken(如何从经过身份验证的 SecurityToken 中获取声明)
本文介绍了如何从经过身份验证的 SecurityToken 中获取声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将令牌作为字符串传递给 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 中获取声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)