Converting a RequestSecurityTokenResponse to a ClaimsIdentity

| | Comments (0) | TrackBacks (0)
Note that this code is only intended for demo and debugging purposes. It doesn't verify the signature of the security token in the RSTR and is not intended to be used in production scenarios.

If you need to convert a RequestSecurityTokenResponse to a ClaimsIdentity, here's one way:

private static ClaimsIdentity GetClaimsIdentity(RequestSecurityTokenResponse rstr)
var rstrXml = rstr.RequestedSecurityToken.SecurityTokenXml;
var xnm = new XmlNamespaceManager(rstrXml.OwnerDocument.NameTable);

xnm.AddNamespace(Saml11Constants.Prefix, Saml11Constants.Namespace);

var attributeStatement = rstrXml.SelectSingleNode("saml:AttributeStatement", xnm);
var attributes = attributeStatement.SelectNodes("saml:Attribute", xnm);
var claims = new List<Claim>();

for (var i = 0; attributes != null && i < attributes.Count; i++)
var attribute = attributes[i];
var claimType = attribute.Attributes["AttributeNamespace"].Value + attribute.Attributes["AttributeName"].Value;
var value = attribute.SelectSingleNode("saml:AttributeValue/text()", xnm).Value;

claims.Add(new Claim(claimType, value ?? ""));

var subject = attributeStatement.SelectSingleNode("saml:Subject/saml:NameIdentifier/text()", xnm).Value;

claims.Add(new Claim(ClaimTypes.Name, subject));

return new ClaimsIdentity(claims);

It assumes that the assertion has an AttributeStatement in it, that that has Attribute elements, that the assertion isn't encrypted, etc. If that isn't necessarily true in your case, adjust as needed. (This code, as all code on my Web site, is licensed under the GNU Public License v. 2.)