事实证明,在 Thinktecture IdentityModel 的帮助下,可以使用 WS-Trust 获取 saml 2.0 令牌和 WebApi 来使用它。以下不包括声明转换,因此如果您需要向 Principal 添加声明,则需要做更多的工作。
webapi 服务的 owin 启动需要使用 Thinktecture.IdentityModel.Owin 中的以下内容:
app.UseSaml2BearerAuthentication(
audience: new Uri(ConfigurationManager.AppSettings["FederatedSecurity.Realm"]),
issuerThumbprint: ConfigurationManager.AppSettings["FederatedSecurity.Thumbprint"],
issuerName: ConfigurationManager.AppSettings["FederatedSecurity.Authority"]);
客户端从 ADFS 请求 saml 2.0 令牌
private static SecurityToken RequestSecurityToken()
{
var trustChannelFactory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(new Uri("https://yourAdfsServer/adfs/services/trust/13/usernamemixed"), new AddressHeader[0]))
{
TrustVersion = TrustVersion.WSTrust13,
Credentials = { UserName = { UserName = @"u$ern@me", Password = "p@ssw0rd" } }
};
var requestSecurityToken = new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
KeyType = KeyTypes.Bearer,
TokenType = TokenTypes.Saml2TokenProfile11,
AppliesTo = new EndpointReference(_audience)
};
RequestSecurityTokenResponse response;
var securityToken = trustChannelFactory.CreateChannel().Issue(requestSecurityToken, out response);
return securityToken;
}
并让客户端调用服务(使用 HttpClient 但 RestSharp 也可以)
private static void CallService(SecurityToken token)
{
using (HttpClient client = new HttpClient())
{
client.SetBearerToken(Convert.ToBase64String(Encoding.UTF8.GetBytes(token.ToTokenXmlString())));
var httpMessage = client.GetAsync(new Uri(_restEndpoint)).Result;
}
}