【问题标题】:Fire event after user is authenticated - windows authentication用户通过身份验证后触发事件 - windows 身份验证
【发布时间】:2014-12-25 16:27:59
【问题描述】:

是否有在用户通过身份验证后触发的事件 (Windows)?我在 Application_Start() 处执行,但它返回 false User.Identity.IsAuthenticated

我想要手动为用户创建和添加角色。

【问题讨论】:

    标签: asp.net-mvc authentication windows-authentication roles application-start


    【解决方案1】:

    我用过这个:

    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 不再为空

    【讨论】:

    • 微软不再推荐在应用程序中使用 NTLM
    • 这是它工作的唯一方式,其他方式 User.Identity.IsAuthenticated 在从 Visual Studio 运行应用程序时为空
    • 你能试试这个吗? stackoverflow.com/questions/1663535/…
    【解决方案2】:

    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");
    

    您可能会发现这篇文章很有用:http://weblogs.asp.net/scottgu/Recipe_3A00_-Implementing-Role_2D00_Based-Security-with-ASP.NET-2.0-using-Windows-Authentication-and-SQL-Server

    【讨论】:

    • 嗨,我在尝试这样: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) { var amduser = new UsuarioDB(); amduser.DefinirPropriedadesUsuario(); } } } } 但 Current.User.Identity 始终为空
    • @user1200656,你能试试这个吗? stackoverflow.com/questions/1663535/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 2013-10-30
    • 1970-01-01
    • 2020-11-04
    • 2016-03-19
    • 2012-03-15
    • 1970-01-01
    相关资源
    最近更新 更多