4

How to get SecurityToken from ClaimsPrincipal?

I need it because I wanna pass it from an MVC application to a WCF service in AuthenticationManager / Authenticate.

In Authenticate method, the value BootstrapContext is null. And even after authenticating, it is getting null sometimes which make it a not reliable choice for me.

This is my Authentication Manager class:

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);
    }
}
Matt Hamsmith
  • 3,955
  • 1
  • 27
  • 42
Homam
  • 23,263
  • 32
  • 111
  • 187

2 Answers2

3

I ended up using this code:

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

You can read more about it in this SO question. It seems that context.SecurityToken will in some time be cleared so one can not depend on it too much.

Community
  • 1
  • 1
pepo
  • 8,644
  • 2
  • 27
  • 42
  • Thanks pepo.. Just wondering if there is a way I can get the GetActAsToken from the IdP without generating it locally again. I'm using Thinktecture. – Homam Nov 14 '14 at 14:13
  • 1
    I stored the ActAs token in a memory cache. I set the expiration of the object (token) in cache some time before actual token expiration. Then, if I did not find the ActAs token for some user, I requested it again from IdP. It worked well for me and to this day I did not have any problems with it. – pepo Nov 14 '14 at 18:51
0
<identityConfiguration saveBootstrapContext="true">

This will save the bootstrap token in ClaimsPrincipal.BootstrapContext.

codewarrior
  • 723
  • 7
  • 22