【发布时间】:2013-12-23 05:35:12
【问题描述】:
我正在使用ASP.NET4.5 with C#。在我的网络应用程序中,实现了一个form authentication,它使用cookie 来存储身份验证信息。
在web.config 中指定为:
<authentication mode="Forms">
<forms loginUrl="~/login.aspx" />
</authentication>
现在,我有一个WCF RESTfull 服务,我正在使用custom basic authentication。对于每个服务调用,我需要设置一个身份验证标头,如果它无效,那么我必须使用401 代码返回响应。
代码如下:
public class BasicAuthenticationInterceptor : RequestInterceptor
{
MembershipProvider provider;
string realm;
public BasicAuthenticationInterceptor(MembershipProvider provider, string realm)
: base(false)
{
this.provider = provider;
this.realm = realm;
}
protected string Realm
{
get { return realm; }
}
protected MembershipProvider Provider
{
get { return provider; }
}
public override void ProcessRequest(ref RequestContext requestContext)
{
HttpRequestMessageProperty request = (HttpRequestMessageProperty)requestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name];
string[] credentials = ExtractCredentials(requestContext.RequestMessage);
if (credentials.Length > 0 && AuthenticateUser(credentials[0], credentials[1]))
{
InitializeSecurityContext(requestContext.RequestMessage, credentials[0]);
}
else
{
try
{
Message reply = Message.CreateMessage(MessageVersion.None, "Invalid Action", "Access Denied");
HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized };
responseProperty.Headers.Add("WWW-Authenticate",
String.Format("Basic realm=\"{0}\"", Realm));
responseProperty.Headers[HttpResponseHeader.ContentType] = "text/html";
reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;
requestContext.Reply(reply);
requestContext = null;
}
catch (Exception ex)
{
throw ex.InnerException;
}
}
}
}
现在,为了防止form authetication 调用WCF,我在web.config 中添加了以下标签:
<location path="MyService.svc">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
请注意,WCF 放置在我项目的“Service”目录中,我尝试在位置选项卡中使用path="~/service/MyService.svc"、path="service/MyService.svc"、path="service",但它返回的是200,而不是@987654339 @代码。
现在,我已经使用Fire-fox RESTClient add-on 测试了服务调用,发现对于invalid request,它仍然返回200 code,而在row-body 中,我得到了HTML 的login.aspx 页面。这意味着它仍在重定向到login.aspx。
如果我将web.config 中的authetication mode 更改为“None”,则服务调用可以正常返回401 代码为invalid request。但我无法将身份验证模式设置为“无”。
请告诉我如何防止 WCF 调用的表单身份验证。
【问题讨论】:
-
您是否验证了 SVC 文件的路径。
-
是的。它在我的应用程序的服务目录中。我用 path="~/service/MyService.svc"、path="service/MyService.svc" 和 path="service" 测试过,但没有得到 401。
-
这些设置是否存在于应用程序根 web.config 中?
-
是的。我的项目中没有任何其他 web.config。
-
有没有专家可用..?
标签: asp.net wcf forms-authentication