我正在构建一个WCF自托管数据服务(顺便说一下,是OData),我正在使用Basic Authentication来验证用户。这并不难,我只需要一些配置步骤,建立一个UserNamePasswordValidator和一个IAuthorizationPolicy - DONE。
现在我需要支持CORS (跨地域资源共享). 我试过很多实现,有些是文档化的(比如。这个),其他的自己做的。
问题是,如果我让Basic Auth启用,因为CORS预飞请求(OPTIONS)没有'Authorization'头,我无法对请求进行操作(当然,否则就违背了浏览器的目的),我无法在服务器上拦截响应请求。我甚至无法检查它到底有多远! 我试着实现了许多Behaviours、Bindings、Manager等,但我无法捕捉到那个请求,甚至在 "DataService<>.OnStartProcessingRequest() "上也无法捕捉到。
如果我禁用Basic Auth 在服务器端,我能够捕获CORS预飞请求并最终响应它(使用IDispatchMessageInspector和BehaviorExtensionElement),但这样一来,我必须自己实现Basic Auth...该死的。
请帮帮我.我如何实现这两个功能?如何在Basic Auth简单地响应401 Unauthorized之前拦截CORS preflight请求?
先谢谢你了。
第一您可以处理您所有的"选项"的请求来允许他们全部。我使用以下技巧:我的服务的接口。
/// <summary>Handles ALL the http options requests.</summary>
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
bool HandleHttpOptionsRequest();
实现。
/// <summary>Handles ALL the http options requests.</summary>
public bool HandleHttpOptionsRequest()
{
if (WebOperationContext.Current != null && WebOperationContext.Current.IncomingRequest.Method == "OPTIONS")
{
return true;
}
return false;
}
第二,您需要添加 访问控制-允许-凭证。 在 "CORS使能器 "中 启用科士
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
var requiredHeaders = new Dictionary<string, string>
{
{ "Access-Control-Allow-Credentials", "true" },
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS" },
{ "Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Safe-Repository-Path,Safe-Repository-Token" }
};
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders));
}
我是如何管理这个问题,在我的情况下,下面提到的 - 。
/// <summary>
/// Class written to check for whether the REST calls is authorised.
/// </summary>
public class RestServiceAuthorizationManger : ServiceAuthorizationManager
{
/// <summary>
/// Method to check for basic authorization in rest service calls.
/// </summary>
protected override bool CheckAccessCore(OperationContext operationContext)
{
try
{
bool Verified = false;
if (WebOperationContext.Current != null &&
WebOperationContext.Current.IncomingRequest.Method == "OPTIONS")
{
WebOperationContext.Current.OutgoingResponse.StatusCode =
HttpStatusCode.OK;
return true;
}
else
{
//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))
{
//You code to check for authorization credientials from incomming authorization headers.
}
else
{
//Throw an exception with the associated HTTP status code equivalent to HTTP status 401
//No authorization header was provided, so challenge the client to provide before proceeding:
//WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"RestServiceAuthorizationManger\"");
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Unauthorized";
return false;
}
}
}
catch(Exception ex)
{
//Throw an exception with the associated HTTP status code equivalent to HTTP status 401
//No authorization header was provided, so challenge the client to provide before proceeding:
//WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"RestServiceAuthorizationManger\"");
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Unauthorized";
return false;
}
}
}
public class EnableCorsSupportBehavior : IEndpointBehavior
{
public void Validate(ServiceEndpoint endpoint)
{
}
public void AddBindingParameters(ServiceEndpoint endpoint,
BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint,
EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
new CorsEnablingMessageInspector());
}
public void ApplyClientBehavior(ServiceEndpoint endpoint,
ClientRuntime clientRuntime)
{
}
}
public class CorsEnablingMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request,
IClientChannel channel, InstanceContext instanceContext)
{
var httpRequest = (HttpRequestMessageProperty)request
.Properties[HttpRequestMessageProperty.Name];
return new
{
origin = httpRequest.Headers["Origin"],
handlePreflight = httpRequest.Method.Equals("OPTIONS",
StringComparison.InvariantCultureIgnoreCase)
};
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
var state = (dynamic)correlationState;
// handle request preflight
if (state != null && state.handlePreflight)
{
reply = Message.CreateMessage(MessageVersion.None, "PreflightReturn");
var httpResponse = new HttpResponseMessageProperty();
reply.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);
httpResponse.SuppressEntityBody = true;
httpResponse.StatusCode = HttpStatusCode.OK;
}
// add allowed origin info
var response = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH, OPTIONS");
response.Headers.Add("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
response.Headers.Add("Access-Control-Allow-Credentials", "true");
}
}
希望能帮到大家。谢谢你