gpt4 book ai didi

c# - 带有 wsHttpBinding 的 WCF 服务 - 操作 HTTP 请求 header

转载 作者:行者123 更新时间:2023-11-30 12:33:33 26 4
gpt4 key购买 nike

我一直在关注this教程,以便在我的 WCF 服务中获得具有传输安全性的用户名身份验证。然而,本教程指的是使用 basicHttpBinding这是 Not Acceptable - 我需要 wsHttpBinding .

想法是有一个自定义 BasicAuthenticationModule在 WCF 服务上,它将从 HTTP 请求中读取“授权” header ,并根据“授权” header 内容执行身份验证过程。问题是缺少“授权” header !

我已经实现了IClientMessageInspector通过自定义行为来操作传出消息并添加自定义 SOAP header 。我在 BeforeSendRequest 中添加了以下代码功能:

    HttpRequestMessageProperty httpRequest = request.Properties.Where(x => x.Key == "httpRequest").Single().Value;
httpRequest.Headers.Add("CustomHeader", "CustomValue");

这应该有效,根据许多网络资源,它适用于 basicHttpBinding但不是 wsHttpBinding .当我说“有效”时,我的意思是 header 已被 WCF 服务成功接收。

这是检查 WCF 服务端接收到的 HTTP 消息的简化函数:

    public void OnAuthenticateRequest(object source, EventArgs eventArgs)
{
HttpApplication app = (HttpApplication)source;

//the Authorization header is checked if present
string authHeader = app.Request.Headers["Authorization"];
if (string.IsNullOrEmpty(authHeader))
{
app.Response.StatusCode = 401;
app.Response.End();
}
}

this 的底帖日期为 2011 年 9 月的线程说 wsHttpBinding 不可能做到这一点.我不想接受这种回应。

附带说明一下,如果我使用 IIS 中内置的基本身份验证模块而不是自定义模块,我会得到

The parameter 'username' must not contain commas.** error message when trying Roles.IsInRole("RoleName") or `[PrincipalPermission(SecurityAction.Demand, Role = "RoleName")]

可能是因为我的 PrimaryIdentity.Name属性包含证书主题名称,因为我正在使用 TransportWithMessageCredential具有基于证书的消息安全性的安全性。

我愿意听取建议以及解决问题的替代方法。谢谢。

更新

看起来,HTTP header 稍后会在整个 WCF 服务代码中被正确读取。 (HttpRequestMessageProperty)OperationContext.Current.IncomingMessageProperties["httpRequest"]包含我的自定义 header 。然而,这已经是消息级的了。如何将 header 传递给传输验证例程?

更新 2
经过一些研究后,我得出一个结论,当 Web 浏览器收到 HTTP 状态代码 401 时,它会向我显示登录对话框,我可以在其中指定我的凭据。但是,WCF 客户端只是抛出异常并且不想发送凭据。我在访问 https://myserver/myservice/service.svc 时能够验证此行为在 Internet Explorer 中。尝试使用来自 this 的信息进行修复链接,但无济于事。这是 WCF 中的错误还是我遗漏了什么?

编辑

这是我的 system.servicemodel 的相关部分(来自 web.config)- 我很确定我的配置是正确的。

  <serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpsGetEnabled="true" httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="ChainTrust" revocationMode="NoCheck" />
</clientCertificate>
<serviceCertificate findValue="server.uprava.djurkovic-co.me" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
</serviceCredentials>
<serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="AspNetSqlRoleProvider" />
</behavior>
</serviceBehaviors>
................
<wsHttpBinding>
<binding name="EndPointWSHTTP" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="20480000" maxReceivedMessageSize="20480000" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="20480000" maxStringContentLength="20480000" maxArrayLength="20480000" maxBytesPerRead="20480000" maxNameTableCharCount="20480000" />
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Basic" />
<message clientCredentialType="Certificate" negotiateServiceCredential="true" algorithmSuite="Default" />
</security>
</binding>
</wsHttpBinding>
............
<service behaviorConfiguration="ServiceBehavior" name="DjurkovicService.Djurkovic">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="EndPointWSHTTP" name="EndPointWSHTTP" contract="DjurkovicService.IDjurkovic" />
</service>

服务返回的异常是:

The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Basic Realm,Negotiate,NTLM'. (The remote server returned an error: (401) Unauthorized.)

最佳答案

有趣的是,当我在写关于上述答案的最后一条评论时,我停了一会儿。我的评论包含“...如果 HTTP header 不包含“授权” header ,我将状态设置为 401,这会导致异常。” 我将状态设置为 401。明白了吗?解决方案一直存在。

初始数据包不包含授权 header ,即使我明确添加它也是如此。但是,正如我在授权模块处于非事件状态时所测试的那样,每个后续数据包都包含它。所以我为什么不尝试将这个初始数据包与其他数据包区分开来呢?因此,如果我看到它是初始数据包,请将 HTTP 状态代码设置为 200(确定),如果不是 - 检查身份验证 header 。这很容易,因为初始数据包在 SOAP 信封(包含 <t:RequestSecurityToken> 标记)中发送对安全 token 的请求。

好吧,让我们看看我的实现,以防其他人需要它。

这是实现 IHTTPModule 的 BasicAuthenticationModule 实现:

public class UserAuthenticator : IHttpModule
{
public void Dispose()
{
}

public void Init(HttpApplication application)
{
application.AuthenticateRequest += new EventHandler(this.OnAuthenticateRequest);
application.EndRequest += new EventHandler(this.OnEndRequest);
}

public void OnAuthenticateRequest(object source, EventArgs eventArgs)
{
HttpApplication app = (HttpApplication)source;

// Get the request stream
Stream httpStream = app.Request.InputStream;

// I converted the stream to string so I can search for a known substring
byte[] byteStream = new byte[httpStream.Length];
httpStream.Read(byteStream, 0, (int)httpStream.Length);
string strRequest = Encoding.ASCII.GetString(byteStream);

// This is the end of the initial SOAP envelope
// Not sure if the fastest way to do this but works fine
int idx = strRequest.IndexOf("</t:RequestSecurityToken></s:Body></s:Envelope>", 0);
httpStream.Seek(0, SeekOrigin.Begin);
if (idx != -1)
{
// Initial packet found, do nothing (HTTP status code is set to 200)
return;
}

//the Authorization header is checked if present
string authHeader = app.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader))
{
if (authHeader == null || authHeader.Length == 0)
{
// No credentials; anonymous request
return;
}

authHeader = authHeader.Trim();
if (authHeader.IndexOf("Basic", 0) != 0)
{
// the header doesn't contain basic authorization token
// we will pass it along and
// assume someone else will handle it
return;
}

string encodedCredentials = authHeader.Substring(6);

byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
string s = new ASCIIEncoding().GetString(decodedBytes);

string[] userPass = s.Split(new char[] { ':' });
string username = userPass[0];
string password = userPass[1];
// the user is validated against the SqlMemberShipProvider
// If it is validated then the roles are retrieved from
// the role provider and a generic principal is created
// the generic principal is assigned to the user context
// of the application

if (Membership.ValidateUser(username, password))
{
string[] roles = Roles.GetRolesForUser(username);
app.Context.User = new GenericPrincipal(new
GenericIdentity(username, "Membership Provider"), roles);
}
else
{
DenyAccess(app);
return;
}
}
else
{
app.Response.StatusCode = 401;
app.Response.End();
}
}

public void OnEndRequest(object source, EventArgs eventArgs)
{
// The authorization header is not present.
// The status of response is set to 401 Access Denied.
// We will now add the expected authorization method
// to the response header, so the client knows
// it needs to send credentials to authenticate
if (HttpContext.Current.Response.StatusCode == 401)
{
HttpContext context = HttpContext.Current;
context.Response.AddHeader("WWW-Authenticate", "Basic Realm");
}
}

private void DenyAccess(HttpApplication app)
{
app.Response.StatusCode = 403;
app.Response.StatusDescription = "Forbidden";

// Write to response stream as well, to give the user
// visual indication of error
app.Response.Write("403 Forbidden");

app.CompleteRequest();
}
}

重要提示:为了让我们能够读取 http 请求流,ASP.NET 兼容性不得启用。

要使您的 IIS 加载此模块,您必须将其添加到 <system.webServer> web.config 部分,如下所示:

<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="BasicAuthenticationModule" />
<add name="BasicAuthenticationModule" type="UserAuthenticator" />
</modules>

但在此之前,你必须确保BasicAuthenticationModule部分未锁定,默认情况下应锁定。如果它被锁定,您将无法更换它。

要解锁模块:(注意:我使用的是 IIS 7.5)

  1. 打开 IIS 管理器
  2. 在左 Pane 中,单击您的主机名
  3. 在中间 Pane 的“管理”部分下,打开“配置编辑器”
  4. 单击上部 Pane 部分“部分”标签旁边的组合框,展开“system.webServer”,然后导航至“模块”
  5. 在“(Collection)”键下,单击“(Count=nn)”值以显示带有“...”的小按钮。点击它。
  6. 在“项目”列表中,找到“BasicAuthenticationModule”并在右 Pane 中单击“解锁项目”(如果存在!)。
  7. 如果您更改了此设置,请关闭配置编辑器并保存更改。

在客户端,您需要能够将自定义 HTTP header 添加到传出消息中。最好的方法是实现 IClientMessageInspector 并使用 BeforeSendRequest 添加您的 header 。功能。我不会解释如何实现 IClientMessageInspector,网上有大量关于该主题的资源。

要将“授权”HTTP header 添加到消息中,请执行以下操作:

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
{

// Making sure we have a HttpRequestMessageProperty
HttpRequestMessageProperty httpRequestMessageProperty;
if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
{
httpRequestMessageProperty = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
if (httpRequestMessageProperty == null)
{
httpRequestMessageProperty = new HttpRequestMessageProperty();
request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessageProperty);
}
}
else
{
httpRequestMessageProperty = new HttpRequestMessageProperty();
request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessageProperty);
}
// Add the authorization header to the WCF request
httpRequestMessageProperty.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(Service.Proxy.ClientCredentials.UserName.UserName + ":" + Service.Proxy.ClientCredentials.UserName.Password)));
return null;
}

好了,解决这个问题花了一些时间,但这是值得的,因为我在整个网络上发现了许多类似的悬而未决的问题。

关于c# - 带有 wsHttpBinding 的 WCF 服务 - 操作 HTTP 请求 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9111361/

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