如何从经过身份验证的 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 中获取声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Custom Error Queue Name when using EasyNetQ for RabbitMQ?(使用 EasyNetQ for RabbitMQ 时自定义错误队列名称?)
How to generate password_hash for RabbitMQ Management HTTP API(如何为 RabbitMQ 管理 HTTP API 生成密码哈希)
Rabbitmq Ack or Nack, leaving messages on the queue(Rabbitmq Ack 或 Nack,将消息留在队列中)
Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Specify Publish timeouts in mass transit(指定公共交通中的发布超时)
RabbitMQ asynchronous support(RabbitMQ 异步支持)