ADFS (Active Directory Federation Services) is a fancy name for Windows Identity Foundation Server. ADFS supports SAML protocol, however its client, Windows Identity Foundation (WIF), does not. As most of the problems of acquiring a token can be resolved with either WS-Federation and WS-Trust, you may use WIF for your federation needs since WIF supports SAML-Token (please notice SAML-Protocol is not the same as SAML-Token).

Lately I have received requests from partners and customers to acquire a SAML Protocol Response which would require SAML-Protocol to request. WIF unfortunately cannot be used to make a SAML-Protocol request and there is no out-of-the-box way of doing that. There are some paid NuGets implementing SAML-Protocol in C#, but none is free. I put together a workaround to request a SAML-Protocol response from ADFS in C# using HttpClient (from System.Net.Http library). System.Net.Http.HttpClient class comes with .NET 4.5 and 4.5.1 and can be added via NuGet to .NET 4.0. The idea is to leverage ADFS Idp Initiated Login page and follow the redirects to extract the SAML Response that happens during the process of logging in to a SAML-Protocol endpoint.

Requirements

You have to create a SAML-Protocol Assertion Endpoint with POST binding in your reliant party configuration. This endpoint can co-exist with a Federation endpoint.

image

Code

I put together two samples. One that shows step-by-step using a Windows Forms application how to acquire a SAML Response (you can download it here):

image

Windows Forms Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. using System.Xml;
  12. using System.Text.RegularExpressions;
  13. using System.Web;
  14. using System.IO;
  15. using System.IO.Compression;
  16.  
  17. //The code samples are provided AS IS without warranty of any kind.
  18. // Microsoft disclaims all implied warranties including, without limitation,
  19. // any implied warranties of merchantability or of fitness for a particular purpose.
  20.  
  21. /*
  22. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you.
  23. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts
  24. be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption,
  25. loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts
  26. or documentation, even if Microsoft has been advised of the possibility of such damages.
  27. */
  28.  
  29. namespace GetSaml
  30. {
  31.     public partial class Form1 : Form
  32.     {
  33.         public Form1()
  34.         {
  35.             InitializeComponent();
  36.         }
  37.  
  38.         private string getUrl = null;
  39.         private string GetUrl
  40.         {
  41.             get
  42.             {
  43.                 if (!String.IsNullOrEmpty(getUrl))
  44.                     return getUrl;
  45.                 StringBuilder domain = new StringBuilder();
  46.                 domain.Append(Environment.GetEnvironmentVariable("USERDNSDOMAIN"));
  47.                 if (domain.Length > 0)
  48.                 {
  49.                     domain.Clear();
  50.                     domain.Append(Environment.UserDomainName);
  51.                 }
  52.                 
  53.                 //return String.Format("https://{0}.{1}.lab/adfs/ls/MyIdpInitiatedSignOn.aspx?loginToRp=https://mysyte.com", Environment.MachineName.ToLower(), Environment.UserDomainName.ToLower());
  54.                 return String.Format("https://{0}.{1}.lab/adfs/ls/IdpInitiatedSignOn.aspx", Environment.MachineName.ToLower(), Environment.UserDomainName.ToLower());
  55.             }
  56.         }
  57.         private void Form1_Load(object sender, EventArgs e)
  58.         {
  59.             textBox1.Text = GetUrl;
  60.         }
  61.  
  62.         protected List<KeyValuePair<string, string>> forms;
  63.  
  64.         private HttpClient client = null;
  65.         private HttpClientHandler handler;
  66.  
  67.         private HttpClient Client
  68.         {
  69.             get
  70.             {
  71.                 if (client == null)
  72.                 {
  73.                     handler = new HttpClientHandler();
  74.                     handler.UseDefaultCredentials = true;
  75.                     handler.AllowAutoRedirect = false;
  76.                     handler.CookieContainer = new System.Net.CookieContainer();
  77.                     handler.UseCookies = true;
  78.                     client = new HttpClient(handler);
  79.                     client.MaxResponseContentBufferSize = 256000;
  80.                     client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
  81.                     client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
  82.                     client.DefaultRequestHeaders.ExpectContinue = false;
  83.  
  84.  
  85.                 }
  86.                 return client;
  87.             }
  88.         }
  89.  
  90.         private async void button1_Click(object sender, EventArgs e)
  91.         {
  92.  
  93.             string url = String.Format("{0}?loginToRp={1}", textBox1.Text, HttpUtility.UrlEncode(comboBox1.SelectedItem.ToString()));
  94.             // Limit the max buffer size for the response so we don't get overwhelmed
  95.             HttpResponseMessage result;
  96.             textBox3.Text="============== Start ===============";
  97.             var nl = Environment.NewLine;
  98.  
  99.        
  100.  
  101.             string text;
  102.             do
  103.             {
  104.  
  105.  
  106.                 textBox3.AppendText(String.Format("{1}********** GET {0}{1}", url, Environment.NewLine));
  107.                 result = await Client.GetAsync(url);
  108.  
  109.  
  110.                 text = await result.Content.ReadAsStringAsync();
  111.                 IEnumerable<string> values;
  112.                 if(result.Headers.TryGetValues("location", out values))
  113.                 {
  114.                     foreach(string s in values)
  115.                     {
  116.  
  117.                         if (s.StartsWith("/"))
  118.                         {
  119.                             url = url.Substring(0, url.IndexOf("/adfs/ls")) + s;
  120.                         }
  121.                         else
  122.                             url = s;
  123.                     }
  124.  
  125.                 } else
  126.                 {
  127.                     url = "";
  128.                 }
  129.                 textBox3.AppendText(String.Format("{0}[Headers]{0}", Environment.NewLine));
  130.                 foreach(var pair in result.Headers)
  131.                 {
  132.                     string key = pair.Key;
  133.                     foreach(var val in pair.Value)
  134.                         textBox3.AppendText(String.Format(" {0}={1}{2}", key, val, Environment.NewLine));
  135.                 }
  136.  
  137.                 textBox3.AppendText(text);
  138.             } while (!String.IsNullOrEmpty(url));
  139.  
  140.  
  141.             Regex reg = new Regex("SAMLResponse\\W+value\\=\\\"([^\\\"]+)\\\"");
  142.             MatchCollection matches = reg.Matches(text);
  143.             string last = null;
  144.             foreach (Match m in matches)
  145.             {
  146.                 last = m.Groups[1].Value;
  147.                 textBox3.AppendText(String.Format(" {1}{1}{1}SAMLResponse={0}{1}", last, Environment.NewLine));
  148.             }
  149.             if(last != null)
  150.             {
  151.  
  152.                 byte[] decoded = Convert.FromBase64String(last);
  153.  
  154.                 string deflated = Encoding.UTF8.GetString(decoded);
  155.                 XmlDocument doc = new XmlDocument();
  156.                 StringBuilder sb = new StringBuilder();
  157.                 doc.LoadXml(deflated);
  158.  
  159.                 using(StringWriter sw = new StringWriter(sb))
  160.                 {
  161.                     using (XmlTextWriter tw = new XmlTextWriter(sw) { Formatting = Formatting.Indented })
  162.                     {
  163.                         doc.WriteTo(tw);
  164.                     }
  165.                 }
  166.                 textBox3.AppendText(String.Format(" {1}{1}{1}XML Formated:{1}{0}{1}", sb.ToString(), Environment.NewLine));
  167.                 
  168.             }
  169.         }
  170.  
  171.  
  172.  
  173.         private void DysplayError(Exception ex)
  174.         {
  175.             MessageBox.Show(String.Format("Error: {0}{1}Stack:{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace));
  176.         }
  177.  
  178.         private async void button2_Click(object sender, EventArgs e)
  179.         {
  180.             try
  181.             {
  182.                 var response = await Client.GetAsync(textBox1.Text);
  183.                 response.EnsureSuccessStatusCode();
  184.                 comboBox1.Items.Clear();
  185.                 string text = await response.Content.ReadAsStringAsync();
  186.                 Regex reg = new Regex("option\\W+value\\=\\\"([^\\\"]+)\\\"");
  187.                 MatchCollection matches = reg.Matches(text);
  188.                 foreach(Match m in matches)
  189.                 {
  190.                     comboBox1.Items.Add(m.Groups[1].Value);
  191.                 }
  192.                 if (matches.Count == 0)
  193.                 {
  194.                     MessageBox.Show("No Reliant Party found");
  195.                     button1.Enabled = false;
  196.                 } else
  197.                 {
  198.                     button1.Enabled = true;
  199.                     comboBox1.SelectedIndex = 0;
  200.                 }
  201.  
  202.             } catch(Exception ex)
  203.             {
  204.                 DysplayError(ex);
  205.                 return;
  206.             }
  207.         }
  208.  
  209.  
  210.     }
  211. }

I also organized the code in a class library that can be used in any C# application. You can download the code and test application here.

Class to get SAML Response
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using System.Net.Http;
  6. using System.Text.RegularExpressions;
  7. using System.Web;
  8. using System.Xml;
  9. using System.IO;
  10.  
  11. //The code samples are provided AS IS without warranty of any kind.
  12. // Microsoft disclaims all implied warranties including, without limitation,
  13. // any implied warranties of merchantability or of fitness for a particular purpose.
  14.  
  15. /*
  16. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you.
  17. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts
  18. be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption,
  19. loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts
  20. or documentation, even if Microsoft has been advised of the possibility of such damages.
  21. */
  22.  
  23. namespace Microsoft.Samples.AdfsSaml
  24. {
  25.     /// <summary>
  26.     /// Class to get a SAML response from ADFS.
  27.     /// it requires that the SAML endpoint with POST binding is configured in ADFS
  28.     /// </summary>
  29.     public class SamlResponse
  30.     {
  31.  
  32.         /// <summary>
  33.         /// If true, ADFS url will not be validated
  34.         /// </summary>
  35.         public bool EnableRawUrl
  36.         {
  37.             get;
  38.             set;
  39.         }
  40.  
  41.         private Uri serverAddress = null;
  42.         private HttpClient client = null;
  43.         private HttpClientHandler handler;
  44.  
  45.         private HttpClient Client
  46.         {
  47.             get
  48.             {
  49.                 if (client == null)
  50.                 {
  51.                     handler = new HttpClientHandler();
  52.                     handler.UseDefaultCredentials = true;
  53.                     handler.AllowAutoRedirect = false;
  54.                     handler.CookieContainer = new System.Net.CookieContainer();
  55.                     handler.UseCookies = true;
  56.                     client = new HttpClient(handler);
  57.                     client.MaxResponseContentBufferSize = 256000;
  58.                     client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
  59.                     client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
  60.                     client.DefaultRequestHeaders.ExpectContinue = false;
  61.                 }
  62.                 return client;
  63.             }
  64.         }
  65.  
  66.         /// <summary>
  67.         /// Url of ADFS server (e.g. https://adfs.contoso.com)
  68.         /// </summary>
  69.         public Uri ServerAddress
  70.         {
  71.             get
  72.             {
  73.                 return serverAddress;
  74.             }
  75.             set
  76.             {
  77.                 if(EnableRawUrl)
  78.                 {
  79.                     serverAddress = value;
  80.                     return;
  81.                 }
  82.                 string host = value.Host;
  83.                 string scheme = value.Scheme;
  84.                 if(scheme != "https")
  85.                 {
  86.                     throw new ArgumentException("ADFS rquires scheme https. Set EnableRawUrl to true to override it", "ServerAddress");
  87.                 }
  88.                 serverAddress = new Uri(String.Format("https://{0}//adfs/ls/IdpInitiatedSignOn.aspx", host));
  89.             }
  90.         }
  91.         /// <summary>
  92.         /// Initialize the class
  93.         /// </summary>
  94.         public SamlResponse()
  95.         {
  96.  
  97.         }
  98.  
  99.         /// <summary>
  100.         /// Initialize the class
  101.         /// </summary>
  102.         /// <param name="Url">Urn of reliant party as defined in ADFS. Ise GetReliantPArtyCollection to get the list</param>
  103.         /// <param name="IsRawUrl">If true, ADFS url will not be validated</param>
  104.         public SamlResponse(Uri Url, bool IsRawUrl = false)
  105.         {
  106.             EnableRawUrl = IsRawUrl;
  107.             ServerAddress = Url;
  108.         }
  109.  
  110.         private async Task<string[]> GetReliantPartyCollectionInternal()
  111.         {
  112.             if (serverAddress == null)
  113.             {
  114.                 throw new NullReferenceException("ServerAddress was not set");
  115.             }
  116.  
  117.             var response = await Client.GetAsync(serverAddress);
  118.             response.EnsureSuccessStatusCode();
  119.             string text = await response.Content.ReadAsStringAsync();
  120.             Regex reg = new Regex("option\\W+value\\=\\\"([^\\\"]+)\\\"");
  121.             MatchCollection matches = reg.Matches(text);
  122.             if(matches.Count == 0)
  123.             {
  124.                 return null;
  125.             }
  126.             string[] rps = new string[matches.Count];
  127.             uint i = 0;
  128.             foreach (Match m in matches)
  129.             {
  130.                 rps[i++]=m.Groups[1].Value;
  131.             }
  132.             return rps;
  133.         }
  134.  
  135.  
  136.         /// <summary>
  137.         /// Get the list of Reliant Parties with SAML endpoint with binding POST in ADFS
  138.         /// </summary>
  139.         public string[] GetReliantPartyCollection()
  140.         {
  141.             return GetReliantPartyCollectionInternal().Result;
  142.         }
  143.  
  144.         /// <summary>
  145.         /// Retrieve the SAML Response from ADFS for ReliantPartyUrn
  146.         /// </summary>
  147.         /// <param name="ReliantPartyUrn">Urn of reliant party as defined in ADFS. Ise GetReliantPArtyCollection to get the list</param>
  148.         public string RequestSamlResponse(string ReliantPartyUrn)
  149.         {
  150.             if(serverAddress == null)
  151.             {
  152.                 throw new NullReferenceException("ServerAddress was not set");
  153.             }
  154.             if(String.IsNullOrEmpty(ReliantPartyUrn) && !EnableRawUrl)
  155.             {
  156.                 throw new ArgumentException("Reliant Party Urn cannot be empty if EnableRawUrl is not true");
  157.             }
  158.  
  159.  
  160.             return SamlResponseInternal(ReliantPartyUrn).Result;
  161.             
  162.         }
  163.  
  164.         private async Task<string> SamlResponseInternal(string ReliantPartyUrn)
  165.         {
  166.  
  167.             StringBuilder url = new StringBuilder(String.Format("{0}?loginToRp={1}", serverAddress, HttpUtility.UrlEncode(ReliantPartyUrn)));
  168.             HttpResponseMessage result;
  169.             
  170.             do
  171.             {
  172.                 result = await Client.GetAsync(url.ToString());
  173.  
  174.                 string text = await result.Content.ReadAsStringAsync();
  175.                 IEnumerable<string> values;
  176.                 if (result.Headers.TryGetValues("location", out values))
  177.                 {
  178.                     foreach (string s in values)
  179.                     {
  180.                         if (s.StartsWith("/"))
  181.                         {
  182.                             string newUrl = url.ToString().Substring(0, url.ToString().IndexOf("/adfs/ls"));
  183.                             url.Clear();
  184.                             url.Append(newUrl);
  185.                             url.Append(s);
  186.                         }
  187.                         else
  188.                         {
  189.                             url.Clear();
  190.                             url.Append(s);
  191.                         }
  192.                     }
  193.  
  194.                 }
  195.                 else
  196.                 {
  197.                     url.Clear();
  198.                 }
  199.                 if (url.Length == 0)
  200.                 {
  201.                     Regex reg = new Regex("SAMLResponse\\W+value\\=\\\"([^\\\"]+)\\\"");
  202.                     MatchCollection matches = reg.Matches(text);
  203.                     foreach (Match m in matches)
  204.                     {
  205.                         return m.Groups[1].Value;
  206.                     }
  207.                 }
  208.  
  209.             } while (url.Length > 0);
  210.             throw new InvalidOperationException("Unable to get a SAMLP response from ADFS");
  211.         }
  212.  
  213.         public static string SamlToXmlString(string EncodedResponse)
  214.         {
  215.             byte[] decoded = Convert.FromBase64String(EncodedResponse);
  216.  
  217.             string deflated = Encoding.UTF8.GetString(decoded);
  218.             XmlDocument doc = new XmlDocument();
  219.             StringBuilder sb = new StringBuilder();
  220.             doc.LoadXml(deflated);
  221.  
  222.             using (StringWriter sw = new StringWriter(sb))
  223.             {
  224.                 using (XmlTextWriter tw = new XmlTextWriter(sw) { Formatting = Formatting.Indented })
  225.                 {
  226.                     doc.WriteTo(tw);
  227.                 }
  228.             }
  229.             return sb.ToString();
  230.  
  231.         }
  232.     }
  233. }