【问题标题】:How to get SecurityToken from ClaimsPrincipal?如何从 ClaimsPrincipal 获取 SecurityToken?
【发布时间】:2014-11-07 12:44:31
【问题描述】:

如何从ClaimsPrincipal获取SecurityToken

我需要它,因为我想将它从 MVC 应用程序传递到 AuthenticationManager / Authenticate 中的 WCF 服务。

在 Authenticate 方法中,BootstrapContext 的值为 null。即使经过身份验证,它有时也会变为空,这对我来说不是一个可靠的选择。

这是我的身份验证管理器类:

public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
    string passportID = incomingPrincipal.Identity.GetPassportID().ToString();

    try
    {
        // I need the token here 
        SecurityToken token = GetToken(incomingPrincipal);
        return base.Authenticate(resourceName, incomingPrincipal);
    }
    catch (Exception ex)
    {
        throw new SecurityException("User is not authenticated.", ex);
    }
}

【问题讨论】:

    标签: .net authentication identity claims-based-identity federated-identity


    【解决方案1】:

    我最终使用了这段代码:

    BootstrapContext context = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext;
    SecurityToken token = context.SecurityToken;
    
    if (context.SecurityToken != null)
    {
        token = context.SecurityToken;
    }
    else if (String.IsNullOrWhiteSpace(context.Token) == false)
    {
        var handlers = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers;
        token = handlers.ReadToken(new XmlTextReader(new StringReader(context.Token)));
    }
    
    var actAsToken = GetActAsToken(token);
    

    您可以在this SO question 中了解更多信息。看来context.SecurityToken会在一段时间内被清除,所以不能太依赖它。

    【讨论】:

    • 感谢 pepo.. 只是想知道是否有一种方法可以从 IdP 获取 GetActAsToken 而无需再次在本地生成它。我正在使用 Thinktecture。
    • 我将 ActAs 令牌存储在内存缓存中。我在实际令牌到期之前的某个时间在缓存中设置了对象(令牌)的到期。然后,如果我没有找到某个用户的 ActAs 令牌,我会再次向 IdP 请求它。它对我来说效果很好,直到今天我都没有遇到任何问题。
    【解决方案2】:
    <identityConfiguration saveBootstrapContext="true">
    

    这会将引导令牌保存在 ClaimsPrincipal.BootstrapContext 中。

    【讨论】:

      猜你喜欢
      • 2016-05-20
      • 2011-02-03
      • 2017-07-25
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多