【问题标题】:Using FormsAuthentication in ASP.NET WebPages在 ASP.NET 网页中使用 FormsAuthentication
【发布时间】:2011-07-18 10:09:47
【问题描述】:

我正在我的 Web 应用程序中为站点管理员设置 FormsAuthentication。这个问题涉及到:Using FormsAuthentication - 我现在的问题是;当管理员“成为现有用户”时,WebSecurity.CurrentUserId 是否填充了他已成为用户的当前用户 ID,还是仍然包含管理员的当前用户 ID?

如果是后者,我们怎样才能让WebSecurity.CurrentUserId 返回他当前冒充的用户的用户 ID?

【问题讨论】:

    标签: c# .net asp.net authentication razor


    【解决方案1】:
    @{
        if(Roles.IsUserInRole("Administrator")) 
        {   
            FormsAuthentication.SetAuthCookie(  
                "joe@harry.com",   
                false
            );
            Response.Redirect("~/Account/Page.cshtml");
        }
    }
    <!DOCTYPE html>
    <html lang="en">
        <body>
            <p>You are now no longer an "admin", but user: @WebSecurity.CurrentUserId</p>
        </body>
    </html>
    

    上面的代码有效。而WebSecurity.CurrentUserId的输出不再是Admin的用户id,而是他刚刚成为的用户的id。

    例子:如果管理员的用户id是3,用户名joe@harry.com的用户id是56,那么用上面的代码,WebSecurity.CurrentUserId的输出就变成了56。

    【讨论】:

    • 因此,如果您需要保留此管理员用户这一事实,则需要独立跟踪。
    • @GalacticCowboy - 感谢您添加额外的内容,我忘了指出这一点;我在这个问题中链接到的上一个问题的评论中也包含了它。
    【解决方案2】:

    FormsAuthentication.SetAuthCookie(string, bool); 可用于登录/注销特定用户,字符串 a username 和 bool 值为 true/false 用于登录/注销。

    FormsAuthentication.SetAuthCookie("user", true); 将登录用户,WebSecurity 将拥有其用户 ID。

    FormsAuthentication.SetAuthCookie("admin", false); 将注销 admin 并将其用户 ID 从 WebSecurity 中删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多