我已经阅读了很多关于这个主题的问题和答案,但没有一个能帮助我解决这个问题。
我遇到的问题是 HttpContext.Current.User
或只是 User
属性的类型是 RolePrincipal
而不是我的自定义类型校长。
这是一个使用 Windows 身份验证的 MVC 5 网络应用程序(仅限 Intranet 应用程序)。我的自定义委托(delegate)人是 WindowsPrincipal
的子类,我确实实现了自己的 RoleProvider
以用于 Authorize 属性标记。
当我尝试通过将主体从当前 HttpContext 上的 IPrincipal
转换为我的自定义主体来使用主体时,我收到一条错误消息,指出它是 RolePrincipal 类型,显然无法将其转换为我的自定义主体.我在 Application_PostAuthenticationRequest
事件中设置我的自定义主体:
protected void Application_PostAuthenticationRequest(object sender, EventArgs e)
{
if (User == null)
return;
using(EntityContext db = new EntityContext ())
{
var user = db.Users.SingleOrDefault(u => u.ADName.Equals(User.Identity.Name));
HttpContext.Current.User = new PcsPrincipal((WindowsIdentity)User.Identity, user);
}
}
当我在该方法中放置一个断点时,它似乎永远不会被调用,这可以解释为什么它没有被设置为我的自定义主体。
我已经审查了以下 QA,但他们未能解决问题:
- using custom IPrincipal and IIdentity in MVC3 - 在 Global.asax.cs 的 Init 方法中添加了事件处理程序的注册。似乎没有什么不同。此外,
_application
变量在 MVC5 中似乎无效。 - RoleProvider dosn't work with custom IIdentity and IPrincipal on server - 在 web.config 文件中进行了更改,但这在运行时导致了各种错误,错误表明 ASP.NET 管道配置不正确。
没有设置 Principal 是我做错了什么?让我知道是否需要发布更多代码。
编辑: 在 WindowsAuthentication.OnAuthenticate 事件中将 HttpContext.Current.User 设置为我的自定义主体并不能解决此问题。使用该方法表现出完全相同的行为。
最佳答案
您应该在应用程序验证当前请求时发生的 WindowsAuthentication_OnAuthenticate 事件中设置自定义主体。
protected void WindowsAuthentication_OnAuthenticate(object source, WindowsAuthenticationEventArgs e)
{
using(EntityContext db = new EntityContext ())
{
var user = db.Users.SingleOrDefault(u => u.ADName.Equals(e.Identity.Name));
HttpContext.Current.User = new PcsPrincipal(e.Identity, user);
}
}
关于c# - MVC5 中无法访问自定义 IPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33220325/