gpt4 book ai didi

c# - 将 SAML token 传递到 Web API 调用

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:13 26 4
gpt4 key购买 nike

我有一个通过 ADFS 进行身份验证的 Web 应用程序和 Web API 服务。它们包含在同一个 IIS 应用程序中,Web 应用程序可以毫无问题地调用 Web API 服务。

我现在正尝试从不同的应用程序调用相同的服务,但在传递 token 时遇到了问题。我能够使用以下代码验证和检索 SAML token :

var stsEndpoint = "https://MyAdfsServer/adfs/services/trust/13/UsernameMixed";
var reliantPartyUri = "https://MyDomain/AppRoot/";

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

factory.TrustVersion = System.ServiceModel.Security.TrustVersion.WSTrust13;

// Username and Password here...
factory.Credentials.UserName.UserName = @"Domain\UserName";
factory.Credentials.UserName.Password = "Password";

var rst = new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
AppliesTo = new EndpointAddress(reliantPartyUri),
KeyType = KeyTypes.Bearer,
};

var channel = factory.CreateChannel();
var token = channel.Issue(rst) as GenericXmlSecurityToken;

var saml = token.TokenXml.OuterXml;

但是,我不确定如何将 saml 传递给网络 api 调用。我试过这个:

using (var handler = new HttpClientHandler() 
{
ClientCertificateOptions = ClientCertificateOption.Automatic,
AllowAutoRedirect = false
})
{
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("https://MyDomain/AppRoot/api/");

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SAML", saml);

HttpResponseMessage response = client.GetAsync("MyService/Get/").Result;

// Get the results...
var result = response.Content.ReadAsStringAsync().Result;
var status = response.StatusCode;
}
}

这将返回状态代码 302 并尝试将我重定向到 ADFS 服务器以进行身份​​验证。还有其他方法可以将 SAML token 传递给 Web API 服务吗?

最佳答案

(设置)

            string samlString = "blah blah blah";

byte[] bytes = Encoding.UTF8.GetBytes(samlString);

string base64SamlString = Convert.ToBase64String(bytes);

myHttpClient.DefaultRequestHeaders.Add("X-My-Custom-Header", base64SamlString);

(获取)

        IEnumerable<string> headerValues = request.Headers.GetValues("X-My-Custom-Header");

if (null != headerValues)

{

var encoding = Encoding.GetEncoding("iso-8859-1");

string samlToken = encoding.GetString(Convert.FromBase64String(headerValues.FirstOrDefault()));

}

关于c# - 将 SAML token 传递到 Web API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22000244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com