![](/img/trans.png)
[英]How can I authenticate to an ASP.NET WebAPI that is using Forms Authentication From a C# Console Application?
[英]How to authenticate a request from a c# application to a WIF enabled ASP.NET WebApi application using a SAML assertion
我已經將ThinkTecture身份服務器設置為STS,已經設置了Web api項目,並在Visual Studio中使用了“身份和訪問”工具,並將其指向我的聯合身份驗證元數據以啟用使用WIF的聯合身份驗證。 這是web.config相關部分的樣子:
<system.identityModel>
<identityConfiguration saveBootstrapContext="true">
<audienceUris>
<add value="http://localhost:41740/" />
</audienceUris>
<securityTokenHandlers>
<add type="System.IdentityModel.Tokens.SamlSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add type="System.IdentityModel.Tokens.Saml2SecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</securityTokenHandlers>
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
<authority name="http://auth.myserver.com/samples">
<keys>
<add thumbprint="F89C10B505E015774D02E323DEDA32878F794028" />
</keys>
<validIssuers>
<add name="http://auth.myserver.com/samples" />
</validIssuers>
</authority>
</issuerNameRegistry>
<!--certificationValidationMode set to "None" by the the Identity and Access Tool for Visual Studio. For development purposes.-->
<certificateValidation certificateValidationMode="None" />
</identityConfiguration>
</system.identityModel>
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="false" />
<wsFederation passiveRedirectEnabled="true" issuer="https://10.40.40.68/issue/wsfed" realm="http://localhost:41740/" requireHttps="false" />
</federationConfiguration>
</system.identityModel.services>
這對於驗證通過瀏覽器使用API的用戶非常有用。
現在,我需要從客戶端應用程序中的代碼(C#)調用相同的API-讓我們使用HTTPClient調用該APIClient。
為了這樣做,我將其添加到了web.config中:
<securityTokenHandlers>
<!--<add type="System.IdentityModel.Tokens.JwtSecurityTokenHandler, System.IdentityModel.Tokens.Jwt" />-->
<add type="System.IdentityModel.Tokens.SamlSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add type="System.IdentityModel.Tokens.Saml2SecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</securityTokenHandlers>
我的假設是,如果我添加SAML令牌處理程序並將SAML斷言添加到HTTP Authorize標頭中,則WIF會選擇並驗證請求。
我可以按照GetSamlToken方法中的說明調用STS來獲取SAML令牌:在此處輸入鏈接描述
這給了我一個附加到HTTPClient標頭的SAML斷言:
client.SetToken("SAML", AuthenticationHeader);
其中AuthenticationHeader是我從服務器收到的SAML斷言。 問題是Web api對samle斷言不做任何事情-好像它甚至都沒有看到,我得到的所有響應都是重定向到STS。
我究竟做錯了什么? 我如何從其他代碼認證和調用受保護的Web api方法,而不必切換到JWT等?
在此先感謝您的幫助!
- 更新
我已按照@Brock的建議將以下內容添加到我的WebApiConfig.cs中:
public static void Register(HttpConfiguration config)
{
// Cross Origin Resource Sharing
//CorsConfig.RegisterCors(GlobalConfiguration.Configuration);
CorsConfig.RegisterCors(config);
//CorsConfiguration corsConfig = new CorsConfiguration();
//corsConfig.AllowAll();
//var corsHandler = new CorsMessageHandler(corsConfig, config);
//config.MessageHandlers.Add(corsHandler);
// authentication configuration for identity controller
var authentication = CreateAuthenticationConfiguration();
config.MessageHandlers.Add(new AuthenticationHandler(authentication));
// ASP.Net web api uses NewtonSoft Json.net natively,
// the following line forces the web api to use the xml serializer instead of data contract serializer
config.Formatters.XmlFormatter.UseXmlSerializer = true;
log.Debug("Registering Web API Routes");
// register api routes
}
private static AuthenticationConfiguration CreateAuthenticationConfiguration()
{
var authentication = new AuthenticationConfiguration
{
ClaimsAuthenticationManager = new ClaimsTransformer(),
RequireSsl = false,
EnableSessionToken = true
};
#region IdentityServer SAML
authentication.AddSaml2(
issuerThumbprint: "F89C10B505E015774D02E323DEDA32878F794028",
issuerName: "https://10.40.40.68/issue/wsfed",
audienceUri: "http://localhost:41740/",//Constants.Realm,
certificateValidator: System.IdentityModel.Selectors.X509CertificateValidator.None,
options: AuthenticationOptions.ForAuthorizationHeader("SAML"),
scheme: AuthenticationScheme.SchemeOnly("SAML"));
#endregion
#region Client Certificates
authentication.AddClientCertificate(ClientCertificateMode.ChainValidation);
#endregion
return authentication;
}
但是我仍然收到302響應。 這是我發出請求的方式:
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
var factory = new WSTrustChannelFactory(
new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
"https://10.40.40.68/issue/wstrust/mixed/username");
factory.TrustVersion = TrustVersion.WSTrust13;
factory.Credentials.UserName.UserName = "myusername";
factory.Credentials.UserName.Password = "password";
var rst = new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
KeyType = KeyTypes.Bearer,
TokenType = Thinktecture.IdentityModel.Constants.TokenTypes.Saml2TokenProfile11,
AppliesTo = new EndpointReference("http://localhost:41740/")
};
var token = factory.CreateChannel().Issue(rst) as System.IdentityModel.Tokens.GenericXmlSecurityToken;
string myToken = token.TokenXml.OuterXml;
HttpClient client = new HttpClient(new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Automatic,
AllowAutoRedirect = false
});
client.SetToken("SAML", myToken);
//client.SetBearerToken(myToken);
var resp = client.GetAsync("http://localhost:41740/api/clients", HttpCompletionOption.ResponseContentRead).Result;
Assert.IsTrue(resp.IsSuccessStatusCode);
Web API v1沒有管道可以自動在請求中查找令牌。 Thinktecture IdentityModel在其Web API身份驗證消息處理程序中提供了此缺少的功能。 檢查樣本文件夾中的示例(特別是AuthenticationConfiguration類和AddSaml2 API):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.