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