Reputation: 4408
I authenticate on ADFS from code and get a decrypted SamlSecurityToken
:
var factory = new WSTrustChannelFactory(
new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
"https://my-adfs-domain.com/adfs/services/trust/13/UserNameMixed")
{
TrustVersion = System.ServiceModel.Security.TrustVersion.WSTrust13,
Credentials =
{
UserName =
{
UserName = "username",
Password = "password"
}
}
};
var token = (GenericXmlSecurityToken)factory.CreateChannel().Issue(
new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
AppliesTo = new EndpointAddress("https://my-service-domain.com"),
KeyType = KeyTypes.Symmetric,
RequestDisplayToken = true
});
SamlSecurityToken decryptedToken;
using (var stream = new MemoryStream())
{
using (var writer = XmlWriter.Create(stream))
token.TokenXml.WriteTo(writer);
stream.Seek(0, SeekOrigin.Begin);
using (var reader = XmlReader.Create(stream))
decryptedToken = (SamlSecurityToken)FederatedAuthentication
.FederationConfiguration.IdentityConfiguration
.SecurityTokenHandlers.ReadToken(reader);
}
var userEmail = decryptedToken.Assertion.Statements
.OfType<SamlAttributeStatement>().Single()
.Attributes[0].AttributeValues[0];
As a next step I'm going to read claims (e.g. user email) from the issued token.
I can extract a part of the related information by code above.
However, I'm looking for a more straightforward and secure way to extract full list of claims from an issued SamlSecurityToken
.
Upvotes: 0
Views: 1592
Reputation: 1759
By far the easiest way to read these claims is to use the built-in Validate method of the Saml2SecurityTokenHandler
. This will convert you security token into a list (generally an 1-element list) of ClaimsIdentity
objects, which in turn
have a Claims
collection. Configuring such a handler from scratch can be a challenge. Therefore you can just use the method you used for reading the token. Call the ValidateToken
on
FederatedAuthentication
.FederationConfiguration.IdentityConfiguration
.SecurityTokenHandlers.ValidateToken()
to get the same result. The Validate
method is a bit of a weird name for this convertion, which makes people search for it.
Upvotes: 3