我有一个网站,使用基本的ASP.Net表单身份验证。在web.config文件中,我们为各个页面和目录指定了特定的访问规则。一切都很好。
然而,现在我有了一些新的要求。我的域包含许多不同的子域之间的许多不同的网站设置。我有两个映射到此应用程序的DNS子域。一个是aaa.mysite.com,另一个是www.mysite.com。如果从子域aaa.mysite.com接收到对受FormsAuthentication保护的页面的特定web请求,则在处理FormsAuthentication逻辑之前(用户将被重定向到登录页面),我想首先执行一些代码。这段代码实际上会尝试从第三个子域(比如zzz.mysite.com )读取cookie,如果不存在,则通过Response.Redirect访问zzz.mysite.com应用程序中的登录页面。
我尝试通过一个基类来处理此问题,然后调用Page_PreInit函数中的特殊代码。但是,即使在调用PreInit函数之前,FormsAuthentication也会处理到登录页面的重定向。
有没有人知道处理这种情况的好方法?如果Page_PreInit不能工作,我可以把代码放在哪里,以便在FormsAuthentication重定向之前执行,但在哪里我也可以访问它所在的页面(以及它从哪个类继承,这样我就可以看到它是从System.Web.UI.Page继承的,还是从我的特殊BasePage继承的)。
有什么想法吗?我想我可以使用全局Application_BeginRequest,但是这样每个请求都会被调用,这看起来不是一个很好的主意。
我不是第一个需要在FormsAuthentication之前处理事件的人,所以如果你能给我一些额外的想法,我将非常感激!
谢谢!
发布于 2010-03-08 19:58:18
如果cookie已写入zzz.example.com
,则www.example.com
上的站点无法读取它-跨子域共享cookie的方法是将它们写入.example.com
。
这可以在表单身份验证中使用web.config中forms element上的domain
属性进行配置:
<forms [...]
domain=".example.com">
注意域名中的前导句点。
编辑以响应评论
您可能应该连接到PostAuthenticateRequest event -这是在建立用户身份(或缺少)之后触发的,并且您可以注册一个custom HttpModule来接收此事件。
显示workings的编辑
好了,我刚刚测试了以下设置:
web应用程序项目,目录结构如下:
/Default.aspx -- Simple aspx page.
/Login.aspx -- Simple aspx page, with a Login control.
/web.config -- Main application config.
/Classes/CheckingAuthenticate.cs -- HttpModule, configured in root.
/Restricted/Default.aspx -- Simple asp page.
/Restricted/web.config -- Config file for authorization
因此,根web.config使用标准的ASP.NET成员资格提供程序设置表单身份验证,并将/Login.aspx
设置为登录页面。我还在其中注册了一个自定义HttpModule:
<httpModules>
<add name="CheckingAuthenticate"
type="TempWebApp.Classes.CheckingAuthenticate"/>
[...]
</httpModules>
/Restricted/
中的web.config拒绝匿名用户访问(这同样可以在根目录中的<location>
元素中完成):
<configuration>
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
然后在我的http模块中有以下代码:
using System;
using System.Web;
using System.Web.Security;
namespace TempWebApp.Classes {
public class CheckingAuthenticate : IHttpModule {
public void Dispose() {
//clean-up code here.
}
public void Init(HttpApplication context) {
context.PostAuthenticateRequest += OnPostAuthenticate;
}
public void OnPostAuthenticate(object sender, EventArgs e) {
var app = sender as HttpApplication;
if (!UrlAuthorizationModule.CheckUrlAccessForPrincipal(app.Request.Path,
app.User,
"GET")){
//Code here to read cookies, redirect user etc.
}
}
}
}
这将在用户通过身份验证之后触发,但在ASP.NET尝试授权用户之前触发,这样您就有机会自己检查访问并进行重定向。我已经很高兴地找到了断点。如果用户没有访问这些页面的权限,我就无法看到AuthorizeRequest或PostAuthorizeRequest事件。
发布于 2010-03-08 19:55:30
我认为您应该使用AuthenticateRequest事件。请参阅lifecycle。不要担心每次请求时都会发生这种情况,很多事情都是这样的。
https://stackoverflow.com/questions/2404154
复制相似问题