2011-02-03 21 views
4

我试图在.NET MVC网站中实现自定义主体和自定义标识。我创建了一个继承自IPrincipal的自定义主体类和一个继承自IIdentity的自定义标识。自定义委托人在新请求中恢复为GenericPrincipal

当用户登录时,我将Thread.CurrentPrincipal和HttpContext.Current.User都设置为我的自定义主体。当我通过调试器查看时,所有的属性都设置了值。

但是,一旦请求完成,我尝试请求任何其他页面,Thread.CurrentPrincipal和HttpContext.Current.User的类型是System.Security.Principal.GenericPrincipal,而不是我的自定义主体。

我是否需要做任何“额外”来让我的自定义主体脱离线程或HttpContext?

由于

回答

6

的值在Thread.CurrentPrincipalHttpContext.Current.User不请求之间依然存在,它们都将被重建对每个请求。你做这件事的最好的地方可能在于Global.asax;写一个函数原型:

void Application_PostAuthenticateRequest(object sender, EventArgs e) 

用户对每个请求验证之后,应该让调用,这将允许您设置主,你怎么想。

0

Overridding主要在:

protected void Application_PostAuthenticateRequest(object sender, EventArgs e) 

而不是

protected void Application_AuthenticateRequest(object sender, EventArgs e) 

在Global.asax.cs中在ASP Web应用程序为我工作

0

我想在接受扩大稍微回答,希望我可以节省一些时间。

就我而言,我使用的委托人包含从外部服务的结果填充的声明,所以我想在登录时缓存结果。

我创建了一个简单的高速缓存接口,IUserPrincipalCache,并将其注册到MVC DependencyResolver。在登录时,我建立了委托人并将其添加到缓存中。 (因为你的执行可能会有所不同,我会离开这一切,。)

然后我实现了这个在Global.asax.cs

protected void Application_PostAuthenticateRequest(object sender, EventArgs e) 
{ 
    if (User.Identity.IsAuthenticated) 
    { 
     var cache = DependencyResolver.Current.GetService<IUserPrincipalCache>(); 
     var claimsPrincipal = cache.FindUser(User.Identity.Name); 
     if (claimsPrincipal != null) 
     { 
      Context.User = claimsPrincipal; 
      Thread.CurrentPrincipal = claimsPrincipal; 
     } 
    } 
} 

我想指出的支票IsAuthenticated是很重要的,因为我可以在许多情况下绕过缓存检查。你也可能不需要更新Thread.CurrentPrincipal,我想这取决于你如何使用它。