How to get a SAML Protocol Response from ADFS using C#


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


Comments (25)

  1. ramon castillo says:

    Most excellent utility.  Thank you.

  2. Todd says:

    I have attempted to use the Form to pull a SAMLResponse from the AWS Relying Party trust off of my ADFS server however it doesn't show the SAMLResponse output anywhere. Thoughts?

  3. Hi Todd,

    I never tested this scenario. Do you have problems if AWS is not the RP? What is the output you get in the text box?

  4. Todd says:

    Yes I have ran this against the 2 other sites in the Target Name drop down list. None show the SAMLResponse.

    It's a lot of text including SAMLRequest and  Page information. Just doesn't include your SAMLResponse shown above. I simply downloaded the Form code, and ran the .exe and put in my adfs server name and then chose the AWS site.

  5. Todd says:

    Do I need to be installing anything before running the GetSaml.exe? I am not a master coder by any means so I was running the form rather than trying to do a C# application.

    Here is the output:

    ============== Start ===============

    ********** GET https://ADFS/adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn%3aamazon%3awebservices

    [Headers]

    Pragma=no-cache

    Cache-Control=no-cache

    Date=Mon, 27 Oct 2014 19:40:24 GMT

    Location=https://ADFS/adfs/ls/?SAMLRequest=7b0HYBxJliUmL23Ke39K9UrX4HShCIBgEyTYkEAQ7MGIzeaS7B1pRyMpqyqBymVWZV1mFkDM7Z28995777333nvvvfe6O51OJ%2fff%2fz9cZmQBbPbOStrJniGAqsgfP358Hz8iHjfZolw9Ol638%2bWr%2fBet86ZNz55%2b9tHvn%2b09zCf5w3z7PLu3u70%2fvT%2fbzvJ7B9v39w5me7uzbDp9%2bPCj9Cfzuimq5Wcf7Y13PkrPmmadny2bNlu29NHO7v727s723oM3uw8f7e882n84%2fnR356c%2bSp9SL8Uya%2fnNeduumkd377Zt0zbjts5mxfKizafzZVVWF0XejKfV4m42O2%2fuls3dj9KTatnkgL%2bul4%2bqrCmaR8tskTeP2umj18dfPH9EqDyaSqNH62WzyqfFeZHPPkrfLcpl84gHvPntVV211bQqPzp6zEOq5dXNL2VNk9cY0kdHGNLtRkSvXBbTvLnb1uumfXxXujt6TIOcFQDWvGfXj4%2fXsyJfTvNXROO6mOJT9%2bERoGSL7AfV8tFVPjG9P75rG7hfAwB3HUL0R59njv4f&Signature=haV26bjGqbuPcg0sywh3h3pwsbZ3WdPy20r2GTax%2b4Or0qVJ9rZiIi4CQToev83N0Iyah%2bi%2btbowVj8Au7HYau43vlSkz%2foQondUYEnkUNHi8PaExLIXZ8vPCVYCWSu%2bbIEHTQh%2fOiGFNRFL47o7eGfdFoc87rmHcTWrxbJyO9BdiHT%2fVvG6h5LjtD%2fk1YbR0ZcMwnJlIujnaYVJ8mp9kc908vsG4Jp8yyUD8f1R09TXjgEGV9oExOjcOHcZf6KDwfp6vRKGXjhaBAivdIbHzlCUsfSjrJIukuif6ng6FKvvqBd%2bNh%2fMjoYXIiGcQ%2bSyPTKsnc%2fJvHM0RKIhvByBgOf2G2ieTlnU2aPf5Vwnzo1nTUwI7PVvIWRDfI1d727pDBhK%2f%2fXFDe%2b9nK8BF3MOYdqWE650ISwhPQyQP9d75DhOdG%2fd%2fRp4q8ogjyb%2fv4oy02szfH66Ezlx1elXn7WQsKC41FgyMFmhqvqJsn7In7tgmXXkKIFhJN13bOIDIqXnef8uZsDGYWG8topaYgnCtgVa6KQr9fQxiI9ZmeJ1TpuXG1WDXmGcwZ4U3yq2hGFebliAzhqj9ePgVShwrFTctKifjrMugBdDE8gQLaQXXBSJC0F54gfG9jYUksYwxT9RUfOB%2b0NvVq4lhIxc3n0nO%2fN3AShDG2jRjzdQ5KTsO4c%3d&SigAlg=http%3a%2f%2fwww.w3.org%2f2001%2f04%2fxmldsig-more%23rsa-sha256

    Server=Microsoft-IIS/7.5

    X-AspNet-Version=2.0.50727

    X-Powered-By=ASP.NET

  6. Todd says:

    <html><head></head><body>

    <h2>Object moved to <a href="https://ADFS/adfs/ls/?SAMLRequest=7b0HYBxJliUmL23Ke39K9UrX4HShCIBgEyTYkEAQ7MGIzeaS7B1pRyMpqyqBymVWZV1mFkDM7Z28995777333nvvvfe6O51OJ%2fff%2fz9cZmQBbPbOStrJniGAqsgfP358Hz8iHjfZolw9Ol638%2bWr%2fBet86ZNz55%2b9tHvn%2b09zCf5w3z7PLu3u70%2fvT%2fbzvJ7B9v39w5me7uzbDp9%2bPCj9Cfzuimq5Wcf7Y13PkrPmmadny2bNlu29NHO7v727s723oM3uw8f7e882n84%2fnR356c%2bSp9SL8Uya%2fnNeduumkd377Zt0zbjts5mxfKizafzZVVWF0XejKfV4m42O2%2fuls3dj9KTatnkgL%2bul4%2bqrCmaR8tskTeP2umj18dfPH9EqDyaSqNH62WzyqfFeZHPPkrfLcpl84gHvPntVV211bQqPzp6zEOq5dXNL2VNk9cY0kdHGNLtRkSvXBbTvLnb1uumfXxXujt6TIOcFQDWvGfXj4%2fXsyJfTvNXROO6mOJT9%2bERoGSL7AfV8tFVPjG9P75rG7hfAwB3HUL0R59njv4f&Signature=haV26bjGqbuPcg0sywh3h3pwsbZ3WdPy20r2GTax%2b4Or0qVJ9rZiIi4CQToev83N0Iyah%2bi%2btbowVj8Au7HYau43vlSkz%2foQondUYEnkUNHi8PaExLIXZ8vPCVYCWSu%2bbIEHTQh%2fOiGFNRFL47o7eGfdFoc87rmHcTWrxbJyO9BdiHT%2fVvG6h5LjtD%2fk1YbR0ZcMwnJlIujnaYVJ8mp9kc908vsG4Jp8yyUD8f1R09TXjgEGV9oExOjcOHcZf6KDwfp6vRKGXjhaBAivdIbHzlCUsfSjrJIukuif6ng6FKvvqBd%2bNh%2fMjoYXIiGcQ%2bSyPTKsnc%2fJvHM0RKIhvByBgOf2G2ieTlnU2aPf5Vwnzo1nTUwI7PVvIWRDfI1d727pDBhK%2f%2fXFDe%2b9nK8BF3MOYdqWE650ISwhPQyQP9d75DhOdG%2fd%2fRp4q8ogjyb%2fv4oy02szfH66Ezlx1elXn7WQsKC41FgyMFmhqvqJsn7In7tgmXXkKIFhJN13bOIDIqXnef8uZsDGYWG8topaYgnCtgVa6KQr9fQxiI9ZmeJ1TpuXG1WDXmGcwZ4U3yq2hGFebliAzhqj9ePgVShwrFTctKifjrMugBdDE8gQLaQXXBSJC0F54gfG9jYUksYwxT9RUfOB%2b0NvVq4lhIxc3n0nO%2fN3AShDG2jRjzdQ5KTsO4c%3d&SigAlg=http%3a%2f%2fwww.w3.org%2f2001%2f04%2fxmldsig-more%23rsa-sha256">here</a&gt;.</h2>

    </body></html>

    ********** GET https://ADFS/adfs/ls/?SAMLRequest=7b0HYBxJliUmL23Ke39K9UrX4HShCIBgEyTYkEAQ7MGIzeaS7B1pRyMpqyqBymVWZV1mFkDM7Z28995777333nvvvfe6O51OJ%2fff%2fz9cZmQBbPbOStrJniGAqsgfP358Hz8iHjfZolw9Ol638%2bWr%2fBet86ZNz55%2b9tHvn%2b09zCf5w3z7PLu3u70%2fvT%2fbzvJ7B9v39w5me7uzbDp9%2bPCj9Cfzuimq5Wcf7Y13PkrPmmadny2bNlu29NHO7v727s723oM3uw8f7e882n84%2fnR356c%2bSp9SL8Uya%2fnNeduumkd377Zt0zbjts5mxfKizafzZVVWF0XejKfV4m42O2%2fuls3dj9KTatnkgL%2bul4%2bqrCmaR8tskTeP2umj18dfPH9EqDyaSqNH62WzyqfFeZHPPkrfLcpl84gHvPntVV211bQqPzp6zEOq5dXNL2VNk9cY0kdHGNLtRkSvXBbTvLnb1uumfXxXujt6TIOcFQDWvGfXj4%2fXsyJfTvNXROO6mOJT9%2bERoGSL7AfV8tFVPjG9P75rG7hfAwB3HUL0R59njv4f&Signature=haV26bjGqbuPcg0sywh3h3pwsbZ3WdPy20r2GTax%2b4Or0qVJ9rZiIi4CQToev83N0Iyah%2bi%2btbowVj8Au7HYau43vlSkz%2foQondUYEnkUNHi8PaExLIXZ8vPCVYCWSu%2bbIEHTQh%2fOiGFNRFL47o7eGfdFoc87rmHcTWrxbJyO9BdiHT%2fVvG6h5LjtD%2fk1YbR0ZcMwnJlIujnaYVJ8mp9kc908vsG4Jp8yyUD8f1R09TXjgEGV9oExOjcOHcZf6KDwfp6vRKGXjhaBAivdIbHzlCUsfSjrJIukuif6ng6FKvvqBd%2bNh%2fMjoYXIiGcQ%2bSyPTKsnc%2fJvHM0RKIhvByBgOf2G2ieTlnU2aPf5Vwnzo1nTUwI7PVvIWRDfI1d727pDBhK%2f%2fXFDe%2b9nK8BF3MOYdqWE650ISwhPQyQP9d75DhOdG%2fd%2fRp4q8ogjyb%2fv4oy02szfH66Ezlx1elXn7WQsKC41FgyMFmhqvqJsn7In7tgmXXkKIFhJN13bOIDIqXnef8uZsDGYWG8topaYgnCtgVa6KQr9fQxiI9ZmeJ1TpuXG1WDXmGcwZ4U3yq2hGFebliAzhqj9ePgVShwrFTctKifjrMugBdDE8gQLaQXXBSJC0F54gfG9jYUksYwxT9RUfOB%2b0NvVq4lhIxc3n0nO%2fN3AShDG2jRjzdQ5KTsO4c%3d&SigAlg=http%3a%2f%2fwww.w3.org%2f2001%2f04%2fxmldsig-more%23rsa-sha256

  7. Todd says:

    [Headers]

    Pragma=no-cache

    Cache-Control=no-cache

    Date=Mon, 27 Oct 2014 19:40:24 GMT

    Server=Microsoft-IIS/7.5

    X-AspNet-Version=2.0.50727

    X-Powered-By=ASP.NET

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/…/xhtml1-transitional.dtd"&gt;

    <html xmlns="http://www.w3.org/…/xhtml&quot; dir="ltr">

    <head><meta http-equiv="X-UA-Compatible" content="IE=8" /><link rel="stylesheet" type="text/css" href="MasterPages/StyleSheet.css" /><meta name="robots" content="noindex, nofollow" /></head>

    <body>

       <form name="aspnetForm" method="post" action="/adfs/ls/?SAMLRequest=7b0HYBxJliUmL23Ke39K9UrX4HShCIBgEyTYkEAQ7MGIzeaS7B1pRyMpqyqBymVWZV1mFkDM7Z28995777333nvvvfe6O51OJ%2fff%2fz9cZmQBbPbOStrJniGAqsgfP358Hz8iHjfZolw9Ol638%2bWr%2fBet86ZNz55%2b9tHvn%2b09zCf5w3z7PLu3u70%2fvT%2fbzvJ7B9v39w5me7uzbDp9%2bPCj9Cfzuimq5Wcf7Y13PkrPmmadny2bNlu29NHO7v727s723oM3uw8f7e882n84%2fnR356c%2bSp9SL8Uya%2fnNeduumkd377Zt0zbjts5mxfKizafzZVVWF0XejKfV4m42O2%2fuls3dj9KTatnkgL%2bul4%2bqrCmaR8tskTeP2umj18dfPH9EqDyaSqNH62WzyqfFeZHPPkrfLcpl84gHvPntVV211bQqPzp6zEOq5dXNL2VNk9cY0kdHGNLtRkSvXBbTvLnb1uumfXxXujt6TIOcFQDWvGfXj4%2fXsyJfTvNXROO6mOJT9%2bERoGSL7AfV8tFVPjG9P75rG7hfAwB3HUL0R59njv4f&Signature=haV26bjGqbuPcg0sywh3h3pwsbZ3WdPy20r2GTax%2b4Or0qVJ9rZiIi4CQToev83N0Iyah%2bi%2btbowVj8Au7HYau43vlSkz%2foQondUYEnkUNHi8PaExLIXZ8vPCVYCWSu%2bbIEHTQh%2fOiGFNRFL47o7eGfdFoc87rmHcTWrxbJyO9BdiHT%2fVvG6h5LjtD%2fk1YbR0ZcMwnJlIujnaYVJ8mp9kc908vsG4Jp8yyUD8f1R09TXjgEGV9oExOjcOHcZf6KDwfp6vRKGXjhaBAivdIbHzlCUsfSjrJIukuif6ng6FKvvqBd%2bNh%2fMjoYXIiGcQ%2bSyPTKsnc%2fJvHM0RKIhvByBgOf2G2ieTlnU2aPf5Vwnzo1nTUwI7PVvIWRDfI1d727pDBhK%2f%2fXFDe%2b9nK8BF3MOYdqWE650ISwhPQyQP9d75DhOdG%2fd%2fRp4q8ogjyb%2fv4oy02szfH66Ezlx1elXn7WQsKC41FgyMFmhqvqJsn7In7tgmXXkKIFhJN13bOIDIqXnef8uZsDGYWG8topaYgnCtgVa6KQr9fQxiI9ZmeJ1TpuXG1WDXmGcwZ4U3yq2hGFebliAzhqj9ePgVShwrFTctKifjrMugBdDE8gQLaQXXBSJC0F54gfG9jYUksYwxT9RUfOB%2b0NvVq4lhIxc3n0nO%2fN3AShDG2jRjzdQ5KTsO4c%3d&SigAlg=http%3a%2f%2fwww.w3.org%2f2001%2f04%2fxmldsig-more%23rsa-sha256" id="aspnetForm">

    <div>

    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTY2MTc3NjUzM2Rk" />

    </div>

    <div>

  8. Are you calling from the same machine ADFS is installed? If so, it will not work because of the loopback check (which you can disable). Short of it, the SAMLRequest seems to be right.

  9. Todd says:

    Character limit, I apologize for having to break it up like this.

  10. Todd says:

    Nope, I am running this from my own machine and targeting the ADFS machine. I was looking to get the SAMLResponse which it just is not giving me in the output.

  11. Todd says:

    I am running the .exe from my own machined and targeting the ADFS server and AWS site. Weird I am not getting that SAMLResponse I need. I should simply just be able to download your code form .exe and run it right?

  12. Todd says:

    Calling from my machine and targeting the ADFS server and AWS relying site I configured. Just doesn't have the SAMLResponse I need to run an API command. I should just be able to download and run the getsaml.exe and target this right, no extra config?

  13. Zubair Mubarik says:

    Thank you for this article, Please advise me how to configure ADFs to Test this code.

    Thank you.

  14. Tim Wallace says:

    I'm new to SSO, ADFS and the like, but unfortunately I got thrown into a project that wants to use their legacy web forms login page but still use the ADFS federation to be able to seamlessly navigate to a partner's site without logging in there as well.  Is the idea of this project that I can build a request using the markup obtained by running your tool and then posting that page to achieve the login?

  15. Tim,

    Federation is a different protocol that is covered in Windows Identity Foundation (WIF). There are several tutorials on how to do that. This is for SAML-Protocol which is not supported in WIF.

  16. Tim Wallace says:

    Rod, I don't/can't use passive federation because the client demands we use their login page.  So I am not fixated on using WIF if I cannot use that in addition to using the existing legacy login page.  I have not found an example of using active federation in a web forms app either, at least not one that relies upon classes and members of classes that have been deprecated.  So if you have any pointers on how I can tweak your code to work in my situation or some other way to accomplish my requirement, I'm all ears.

  17. Tim Wallace says:

    Rod, I replied earlier, but it appears not to have taken.  I cannot use passive federation since the client wants to use their legacy login page. I am open to options other than WIF. The client still wants to do SSO with partners, so somehow I have to get that security token from the ADFS box.  Any suggestions?

  18. Tim,

    You need to use WS-Trust 1.3 to request a bearer token from ADFS and use this token to call the 3rd-party: leastprivilege.com/…/wcf-and-identity-in-net-4-5-external-authentication-with-ws-trust

  19. Tim Wallace says:

    Rod, thanks for the link.  I had already found that link.  My problem is that the sample code does not compile ( WSTrustChannelFactory no longer has a "Credentials" member, for example) and I am not familiar enough with the inner workings of WS-Trust to determine the current way of accomplishing what the sample code suggests.

  20. Tim,

    Right now I am on vacation without a development environment. Post a question to the WIF forum at MSDN so someone can follow up with this. Don't forget to mention your .NET version.

  21. Daniel says:

    Where is the authentication?  Shouldn't you post the username, password and SAMLResponse to the relying party?

    I've extracted the contents of the authentication flow between browser -> RP, browser -> ADFS and browser -> RP again with Fiddler and wanted to replicate in code this without the ADFS login form showing. Its a poor man's version of single sign on.  

    Its similar to what you're doing, but its brute force and also could it be a kind of replay attack?

    What is the Single Sign On solution for Windows7 development using ADFS 3.0?

  22. Daniel,

    Password is not passed over, but a NTLM or Kerberos token instead. SAML tokens do not contain a password, only the claims configured for the reliant party (RP). If the RP configuration includes a signing certificate even the claims are encrypted at message level, so Fiddler reverse-engineer is of no use.

    ADFS does not make a brute force attack any easier. My application (and library) is not getting any data that would not be available to the person authenticating.

  23. Michael Meinhardt says:

    Thanks Rodney! I banged my head against the wall for two weeks on this – There’s a dearth of information, most of it irrelevant. The frustrating part is I had done essentially what you did there – I recorded what was passed back from the IDP initiated login. The simplest answers are usually the best 🙂 – Thanks again for a great write-up!

    1. paul says:

      So did you get this to work? Are you authenticating with ADFS in terms of retrieving specific information our to be authenticated for SSO purposes?

      We’re wanting to use our custom app to authenticate with ADFS for SSO purposes but without actually directing the user to the ADFS IdpInitiatedSignOn.aspx page. From what I’ve read and tried, this is not possible and the request to authenticate with ADFS to get an SSO token has to originate from the ADFS sign on page…

      What we’re wanting to do:: user signs into our custom app, custom app then authenticates said user to ADFS (“in the background”) returning the authenticated token back to our custom app. Now linking to any relying party trust apps connected to ADFS via our custom app the user will already be signed in….

      We are wanting to due this to to multiple reasons, including: our custom app has multiple audiences, both with AD accounts and those without.. 2. the ADFS sign on page is hardly customizable, wouldn’t be able to make it look anything like our custom app login page.

Skip to main content