使用 Windows 凭据从 ADFS 获取 SAML 令牌

问题描述 投票:0回答:2

我正在用c#创建一个Windows 8客户端应用程序。该应用程序将使用SAP的odata服务。对于身份验证,我需要 ADFS 颁发的 SAML 令牌。有没有任何方法可以使用 Windows 凭据从 ADFS 获取 SAML 令牌?

c# windows-8 sap saml
2个回答
0
投票

您可以使用以下代码获取 SAML 令牌。

var factory = new WSTrustChannelFactory(new Microsoft.IdentityModel.Protocols.WSTrust.Bindings.UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), adfsEndpoint);

factory.Credentials.UserName.UserName = "username";
factory.Credentials.UserName.Password = "********";
factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
factory.TrustVersion = TrustVersion.WSTrust13;
WSTrustChannel channel = null;
try
{
    var rst = new RequestSecurityToken
    {
        RequestType = WSTrust13Constants.RequestTypes.Issue,
        AppliesTo = new EndpointAddress("https://yourserviceendpoint.com/"),
        KeyType = KeyTypes.Bearer,
    };
    channel = (WSTrustChannel)factory.CreateChannel();
    return channel.Issue(rst);
}
catch (Exception e)
{
    return null;
}

0
投票

您可以通过以下代码获取SAML Token


protected HttpClient Client
{
    get
    {
        if (client == null)
        {
            handler = new HttpClientHandler();
        handler.Credentials = new NetworkCredential(username, password);
        handler.AllowAutoRedirect = false;
        handler.CookieContainer = cookies;
        handler.UseCookies = true;
        client = new HttpClient(handler);
        client.MaxResponseContentBufferSize = 9999999;
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
        client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
        client.DefaultRequestHeaders.ExpectContinue = false;
    }
    return client;
}

}

public String GetSAML() {
try { if (client != null) { client = null; }

    text = "";
    String SAMLTokenBase64String="";
    String urlRelayParty = "Your_domain_party_identifier";
    string url = String.Format("{0}?loginToRp={1}", "https://***yourdomainforstsoradfs*****.com/adfs/ls/IdpInitiatedSignOn.aspx", HttpUtility.UrlEncode(urlRelayParty));
    try
    {
        do
        {
            result = Client.GetAsync(url).GetAwaiter().GetResult();
            text = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            IEnumerable<string> values;
            if (result.Headers.TryGetValues("location", out values))
            {
                foreach (string s in values)
                {
                    if (s.StartsWith("/"))
                    {
                        url = url.Substring(0, url.IndexOf("/adfs/ls")) + s;
                    }
                    else
                        url = s;
                }
            }
            else
            {
                url = "";
            }
        }
        while (!String.IsNullOrEmpty(url));
    }
    catch (Exception ex)
    {
        ErrorLogger.MakeExLog(902, ex, badgeno);
    }

    Regex reg = new Regex("SAMLResponse\\W+value\\=\\\"([^\\\"]+)\\\"");
    MatchCollection matches = reg.Matches(text);
    foreach (Match m in matches)
    {
        SAMLTokenBase64String = m.Groups[1].Value;
    }

    if (SAMLTokenBase64String != null && SAMLTokenBase64String.Trim().Length > 0)
    {
        SB("STS Login Successfull for " + urlRelayParty);
        return SAMLTokenBase64String;
    }
}
catch (Exception ex)
{
}

SB("STS Login Failed for " + urlRelayParty);
return "";

        handler.Credentials = new NetworkCredential(username, password);
        handler.AllowAutoRedirect = false;
        handler.CookieContainer = cookies;
        handler.UseCookies = true;
        client = new HttpClient(handler);
        client.MaxResponseContentBufferSize = 9999999;
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
        client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
        client.DefaultRequestHeaders.ExpectContinue = false;
    }
    return client;
}

© www.soinside.com 2019 - 2024. All rights reserved.