As mentioned in a previous blog post, this class takes care of the interaction with the ADFS server.
Its main functionality is to request and decrypt SAML tokens from an ADFS server.
The class makes use of the .NET security token API, which in order to be used, it has to be configured. The easiest is to configure it through XML, in one of the application's .config files:
The configuration above allows us to use the predefined System.IdentityModel.Tokens.Saml2SecurityTokenHandler. I used this class to handle the reading (i.e. decrypting) and validating (i.e. extracting the claims) the token. If configured correctly, this class makes the entire token handling quite easy.
The configuration above refers to the SSL Certificate that must be installed on the machine running the AdfsClient, and basically configures a way of looking up the certificate by its thumbprint. This certificate is used to decrypt the encrypted SAML XML token, so it must contain a private key. This same certificate (only the public key) is configured in the ADFS Relying Party encryption panel and it is used by the ADFS server to encrypt the token when it's issued.
The constructors above are self explanatory, but they also initialize the current instance.
The method GetToken below, requests a token from the ADFS server, but only if there is no token already present in the internal cache. This is done in order to prevent requesting a new token for every single request. The cache key is constructed based off the user, password hash, audienceUri and STS endpoint.
A token is placed into cache for the duration that token is valid, as specified in the token itself.
Next, method DecryptSaml2Token takes a string representation of the SAML token, as it was received from the ADFS server, and decodes it into a generic XML token and at the same time decrypts the encrypted part of the XML. This method is used during passive-authentication from the ADFS, namely in the previously explained SamlAuthenticationHandler.
The method uses a StringReader to identify where the token starts in the XML, and then uses the ReadToken method of the SecyrityTokenHandlers collection.
The method DecryptToken below, decrypts a GenericXmlSecurityToken token and returns a SecurityToken, which represents a specific decrypted security token, but under a generic type. Since we know we are requesting SAML2 tokens from ADFS, it's safe to assume this token is in fact a Saml2SecurityToken that contains claims.
Also this method removes the object from cache, in case the decryption fails.
Next, the method GetPrincipal reads the claims inside the token and extracts them in a collection of ClaimsIdentity objects by calling the ValidateToken method on the SecurityTokenHandlers collection.
It returns a ClaimsPrincipal object based off this claims.
Its main functionality is to request and decrypt SAML tokens from an ADFS server.
The class makes use of the .NET security token API, which in order to be used, it has to be configured. The easiest is to configure it through XML, in one of the application's .config files:
<system.identityModel.services> <federationConfiguration> <serviceCertificate> <certificateReference storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint" findValue="30 4e 10 91 73 fb 34 6a 90 19 f5 e7 d4 fa 2d 11 21 10 3e 3d"/> </serviceCertificate> </federationConfiguration> </system.identityModel.services>
The configuration above allows us to use the predefined System.IdentityModel.Tokens.Saml2SecurityTokenHandler. I used this class to handle the reading (i.e. decrypting) and validating (i.e. extracting the claims) the token. If configured correctly, this class makes the entire token handling quite easy.
The configuration above refers to the SSL Certificate that must be installed on the machine running the AdfsClient, and basically configures a way of looking up the certificate by its thumbprint. This certificate is used to decrypt the encrypted SAML XML token, so it must contain a private key. This same certificate (only the public key) is configured in the ADFS Relying Party encryption panel and it is used by the ADFS server to encrypt the token when it's issued.
public const string SAML2_ASSERTION = "urn:oasis:names:tc:SAML:2.0:assertion"; private SecurityTokenHandlerCollection securityTokenHandlers; private SecurityTokenHandlerCollection SecurityTokenHandlers { get { if (securityTokenHandlers == null) { securityTokenHandlers = new SecurityTokenHandlerCollection( FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers); for (int i = 0; i < securityTokenHandlers.Count; i++) { if (securityTokenHandlers[i] is Saml2SecurityTokenHandler) { securityTokenHandlers[i] = new ValidatingSaml2SecurityTokenHandler { Configuration = securityTokenHandlers[0].Configuration }; } } } return securityTokenHandlers; } } public AdfsClient() { IsInitialized = false; } public AdfsClient(string username, string password, string audienceUri, string stsEndpoint) { IsInitialized = true; Username = username; Password = password; AudienceUri = audienceUri; StsEndpoint = stsEndpoint; }
The constructors above are self explanatory, but they also initialize the current instance.
The method GetToken below, requests a token from the ADFS server, but only if there is no token already present in the internal cache. This is done in order to prevent requesting a new token for every single request. The cache key is constructed based off the user, password hash, audienceUri and STS endpoint.
A token is placed into cache for the duration that token is valid, as specified in the token itself.
public GenericXmlSecurityToken GetToken() { if (!IsInitialized) { throw new AdfsClientException("AdfsClinet not initialized"); } GenericXmlSecurityToken token; if (!cache.TryGet(CacheKey, out token)) { WSHttpBinding binding = new WSHttpBinding(); binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName; binding.Security.Message.EstablishSecurityContext = false; binding.Security.Mode = SecurityMode.TransportWithMessageCredential; var endpoint = new EndpointAddress(StsEndpoint); using (var factory = new WSTrustChannelFactory(binding, endpoint)) { factory.Credentials.UserName.UserName = Username; factory.Credentials.UserName.Password = Password; IWSTrustChannelContract channel = factory.CreateChannel(); RequestSecurityToken request = new RequestSecurityToken { RequestType = RequestTypes.Issue, AppliesTo = new EndpointReference(AudienceUri), TokenType = SAML2_ASSERTION }; token = (GenericXmlSecurityToken)channel.Issue(request); cache.Insert(CacheKey, token, token.ValidTo - token.ValidFrom); } } return token; }
Next, method DecryptSaml2Token takes a string representation of the SAML token, as it was received from the ADFS server, and decodes it into a generic XML token and at the same time decrypts the encrypted part of the XML. This method is used during passive-authentication from the ADFS, namely in the previously explained SamlAuthenticationHandler.
The method uses a StringReader to identify where the token starts in the XML, and then uses the ReadToken method of the SecyrityTokenHandlers collection.
public Saml2SecurityToken DecryptSaml2Token(string tokenXml) { using (StringReader stringReader = new StringReader(tokenXml)) using (XmlReader reader = XmlReader.Create(stringReader)) { reader.ReadToFollowing("EncryptedAssertion", SAML2_ASSERTION); return (Saml2SecurityToken)SecurityTokenHandlers.ReadToken(reader); } }
The method DecryptToken below, decrypts a GenericXmlSecurityToken token and returns a SecurityToken, which represents a specific decrypted security token, but under a generic type. Since we know we are requesting SAML2 tokens from ADFS, it's safe to assume this token is in fact a Saml2SecurityToken that contains claims.
Also this method removes the object from cache, in case the decryption fails.
public SecurityToken DecryptToken(GenericXmlSecurityToken encryptedToken) { try { var reader = new XmlNodeReader(encryptedToken.TokenXml); return SecurityTokenHandlers.ReadToken(reader); } catch (Exception e) { cache.Remove<object>(CacheKey); throw new AdfsClientException("Unable to decrypt token", e); } }
Next, the method GetPrincipal reads the claims inside the token and extracts them in a collection of ClaimsIdentity objects by calling the ValidateToken method on the SecurityTokenHandlers collection.
It returns a ClaimsPrincipal object based off this claims.
public ClaimsPrincipal GetPrincipal(SecurityToken decryptedToken) { try { ReadOnlyCollection<ClaimsIdentity> identities = SecurityTokenHandlers.ValidateToken(decryptedToken); return new ClaimsPrincipal(identities[0]); } catch (Exception e) { cache.Remove<object>(CacheKey); throw new AdfsClientException("Unable to validate token", e); } }
Comments