WCF——REST和SOAP的多个端点
本文关键字:端点 SOAP REST WCF | 更新日期: 2023-09-27 18:18:19
我正在尝试编写具有REST和SOAP端点的WCF服务。我最初对SOAP端点使用"TransportCredentialOnly"。当我开始添加REST端点时……我使用第三方OAUTH 1.0类为REST服务提供安全性。
使用"TransportCredentialOnly"身份验证,我必须在IIS网站应用程序上启用"Windows身份验证"。
我遇到的问题是REST调用返回"身份验证失败",因为IIS期望在击中REST端点之前使用Windows凭据进行初始身份验证。
我在IIS应用程序上启用了"匿名身份验证",但在继续之前仍然提示需要Windows凭据。
无论如何要保持SOAP调用的"Windows身份验证"方案,并在REST端点上进行匿名身份验证(这将继续使用OAuth 1.0)?我真的不想把它分成两个项目/服务,因为有些函数/方法/类在SOAP和REST调用之间是通用的。
这是我到目前为止尝试的web配置:
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
<authentication mode="Windows"/>
<authorization>
<allow roles="DOMAIN'Security_Group"/>
<deny users="*"/>
</authorization>
<customErrors mode="Off"/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
</security>
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP" />
</webHttpBinding>
</bindings>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="Anonymous">
<security mode="None"/>
</standardEndpoint>
</webHttpEndpoint>
</standardEndpoints>
<services>
<service name="service name">
<endpoint address="SOAP"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpEndpointBinding"
contract="contract name">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="REST"
kind="webHttpEndpoint"
binding ="webHttpBinding"
bindingConfiguration="webHttpBindingWithJsonP"
endpointConfiguration="Anonymous"
behaviorConfiguration="restBehavior"
contract ="contract name">
</endpoint>
<host>
<baseAddresses>
<add baseAddress="service url"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="restBehavior">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<useRequestHeadersForMetadataAddress/>
</behavior>
</serviceBehaviors>
</behaviors>
<!--<protocolMapping>
<add binding="basicHttpsBinding" scheme="http" />
</protocolMapping>-->
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<!--<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Methods" value="POST,GET"/>
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept"/>-->
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
10-20-2015更新:我应用了一个新的配置来在web中使用serviceAuthorization。配置文件
<service name="service name" behaviorConfiguration="Oauth">
<endpoint address="service address"
binding ="webHttpBinding"
behaviorConfiguration="restBehavior"
contract ="service contract">
</endpoint>
<host>
<baseAddresses>
<add baseAddress="base address"/>
</baseAddresses>
</host>
</service>
<behavior name="Oauth">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceAuthorization serviceAuthorizationManagerType="Assembly.OAuthAuthorizationManager,Assembly" />
</behavior>
下面是OAuthorizationManager类:
public class OAuthAuthorizationManager : ServiceAuthorizationManager
{
protected override bool CheckAccessCore(OperationContext operationContext)
{
bool Authenticated = false;
string normalizedUrl;
string normalizedRequestParameters;
base.CheckAccessCore(operationContext);
// to get the httpmethod
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)(operationContext.RequestContext.RequestMessage).Properties[HttpRequestMessageProperty.Name];
string httpmethod = requestProperty.Method;
// HttpContext.Current is null, so forget about it
// HttpContext context = HttpContext.Current;
NameValueCollection pa = HttpUtility.ParseQueryString(operationContext.IncomingMessageProperties.Via.Query);
if (pa != null && pa["oauth_consumer_key"] != null)
{
// to get uri without oauth parameters
string uri = operationContext.IncomingMessageProperties
.Via.OriginalString.Replace
(operationContext.IncomingMessageProperties
.Via.Query, "");
string consumersecret = "secret";
OAuthBase oauth = new OAuthBase();
string hash = oauth.GenerateSignature(
new Uri(uri),
pa["oauth_consumer_key"],
consumersecret,
null, // totken
null, //token secret
httpmethod,
pa["oauth_timestamp"],
pa["oauth_nonce"],
out normalizedUrl,
out normalizedRequestParameters
);
Authenticated = pa["oauth_signature"] == hash;
}
return Authenticated;
}
}
有一个可行的解决方案,让托管在IIS中的基于REST的WCF服务可以使用它自己的自定义基本身份验证。你可以很容易地发送回一个响应头来挑战基本身份验证凭据,并且只需将IIS连接到"Anonymous Authentication."
。在这种情况下,IIS将只负责托管,就是这样。
创建一个自定义授权管理器类,它继承自ServiceAuthorizationManager
,并将其配置到您的服务。
public class RestAuthorizationManager : ServiceAuthorizationManager
{
protected override bool CheckAccessCore(OperationContext operationContext)
{
//Extract the Authorization header, and parse out the credentials converting the Base64 string:
var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
if ((authHeader != null) && (authHeader != string.Empty))
{
var svcCredentials = System.Text.ASCIIEncoding.ASCII
.GetString(Convert.FromBase64String(authHeader.Substring(6)))
.Split(':');
var user = new { Name = svcCredentials[0], Password = svcCredentials[1] };
if ((user.Name == "user1" && user.Password == "test"))
{
//User is authrized and originating call will proceed
return true;
}
else
{
//not authorized
return false;
}
}
else
{
//No authorization header was provided, so challenge the client to provide before proceeding:
WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm='"MyWCFService'"");
//Throw an exception with the associated HTTP status code equivalent to HTTP status 401
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
}
}
将上述自定义授权管理器添加到配置中:
<serviceBehaviors>
<behavior name="SecureRESTSvcTestBehavior">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/>
<serviceAuthorization serviceAuthorizationManagerType="WcfRestAuthentication.Services.Api.RestAuthorizationManager, WcfRestAuthentication"/>
</behavior>
</serviceBehaviors>
仅对REST端点应用上述行为。现在IIS将不再控制这里的任何授权。请确保使用SSL证书来保护凭证不会以纯文本形式发送。