【发布时间】:2014-12-25 16:27:59
【问题描述】:
是否有在用户通过身份验证后触发的事件 (Windows)?我在 Application_Start() 处执行,但它返回 false User.Identity.IsAuthenticated。
我想要手动为用户创建和添加角色。
【问题讨论】:
标签: asp.net-mvc authentication windows-authentication roles application-start
是否有在用户通过身份验证后触发的事件 (Windows)?我在 Application_Start() 处执行,但它返回 false User.Identity.IsAuthenticated。
我想要手动为用户创建和添加角色。
【问题讨论】:
标签: asp.net-mvc authentication windows-authentication roles application-start
我用过这个:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is WindowsIdentity)
{
if (string.IsNullOrEmpty(Usuario.Nome))
{
确保,在您的项目属性中(alt + 在项目中输入)单击 WEB 并检查 NTLM AUTHENTICATION。
这对我有用。现在HttpContext.Current.User.Identity 不再为空
【讨论】:
Application_Start() 在 ASP.NET 应用程序中的第一个资源(例如页面)被请求时被调用。此外,它在应用程序的生命周期中只调用一次。话虽如此,届时您将无法对所有用户进行身份验证。客户端计算机上的当前 Windows 用户信息由 Web 浏览器通过涉及与 Web 服务器 [Wiki] 散列的加密交换提供。只有这样您才能对用户进行身份验证。因此,User.Identity.IsAuthenticated 应该在页面加载时工作(参见下面的代码)。您可以将所需的逻辑提取到一个通用方法中,并在页面第一次加载时调用它
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
Page.Title = "Home page for " + User.Identity.Name;
// add your logic here
}
else
{
// you get here if auth failed.
Page.Title = "Home page for guest user.";
}
}
更新后的更多信息:
如果角色不存在,我会使用 Application_Start() 检查和添加角色。
if (! Roles.RoleExists("Auditors"))
Roles.CreateRole("Auditors");
【讨论】: