窗体身份验证理解context.user.identity [英] Forms Authentication understanding context.user.identity

查看:257
本文介绍了窗体身份验证理解context.user.identity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于在此过程中的文档是非常模糊和混乱(或旧的),我想确认我在做正确且没有遗漏任何步骤。

Since documentation on this process is very vague and confusing (or old), I wanted to verify that I was doing it correctly and not missing any steps.

我想创建一个安全的登录系统,在该浏览器的紧密到期。

I am trying to create a secure login system, that expires on browser-close.

- 在我的web.config我有以下 -

-- in my web.config I have the following --

<authentication mode="Forms">
      <forms loginUrl="~/Login.aspx" defaultUrl="Index.aspx" name=".ASPXFORMSAUTH" timeout="100" />
    </authentication>
    <authorization>
      <allow users="?" />
    </authorization>
    <machineKey decryption="AES" validation="SHA1" validationKey.......... />

所以我有一个用户名/密码文本框和这个按钮登录表单:

So I have a login form with username/password textbox and this button:

<asp:Button ID="LoginButton" runat="Server" OnClick="Login_Authenticate" Text="Sign in" />

里面Login_Authenticate我做到以下几点:

Inside Login_Authenticate I do the following:

protected void Login_Authenticate(object sender, EventArgs e){
string userName = UserName.Text;
string password = Password.Text;

bool Authenticated = false;

// Here's code that makes sure that Username and Password is CORRECT
if(AuthClass.Authenticate(userName, password)){
 Authenticated = true;
}
// error checking does happen here.

if (Authenticated)
{
  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), rememberUserName, String.Empty, FormsAuthentication.FormsCookiePath);
  string encryptedCookie = FormsAuthentication.Encrypt(ticket);
  HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookie);
  cookie.Expires = DateTime.Now.AddMinutes(30);
  Response.Cookies.Add(cookie);
  //FormsAuthentication.RedirectFromLoginPage(userName, false);

  Response.Redirect("MainPage.aspx");
}
}

在---我在Page_Init()以下的检查MasterPage.master.cs ---

--- in the MasterPage.master.cs I have the following check in Page_Init() ---

if (Context.User.Identity.IsAuthenticated)
    {
      int userid = (int)Session["userid"];
      if (userid == null)
      {
        userid = GetUserID(Context.User.Identity.Name);
        if (userid != null)
        {
          Session["userid"] = userid;
        }
      }
    }

编辑:
--- Global.asax中;一些code,我不太肯定是正确的或不知道它做什么

protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        // look if any security information exists for this request
        if (HttpContext.Current.User != null)
        {
            // see if this user is authenticated, any authenticated cookie (ticket) exists for this user
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                // see if the authentication is done using FormsAuthentication
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    // Get the roles stored for this request from the ticket
                    // get the identity of the user
                    FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
                    //Get the form authentication ticket of the user
                    FormsAuthenticationTicket ticket = identity.Ticket;
                    //Get the roles stored as UserData into ticket
                    string[] roles = { };
                    //Create general prrincipal and assign it to current request

                    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
                }
            }
        }
    }

---从那时起,每一页上,我使用Session用户ID来收集用户信息和内容,并确保用户有适当的认证和组角色权限。

--- from then on, on every page, I use the Session userid to gather the user information and content and make sure the user has proper authentication and group-role permissions.

这是正确的?还是我在什么地方解密什么?

Is this all correct? Or do I have to Decrypt anything somewhere?

这是足以让一个安全的用户登录?或者我应该不窗体身份验证打扰,找到我自己的方式,使我自己的cookies和管理它自己?

Is this enough to make a secure user login? Or should I not bother with forms authentication and find my own way to make my own cookies and manage it myself?

推荐答案

您code被写入登录将在浏览器会话持续的方式。这可能有助于了解正在发生的事情的基础。

The way your code is written logins will persist across browser sessions. It might help to understand the basics of what is going on.

有关基于cookie的身份验证方法,真的有三个动作:

For cookie based authentication methods, there are really three actions:

1)登录 - 验证用户的凭据,并创建和浏览器存储的cookie

1) Login - validates user's credentials and creates and stores a cookie on their browser.

2)注销 - 只是从浏览器cookie的(由过期饼干或删除吧)

2) Logout - simply removes the cookie from the browser (by expiring the cookie or deleting it)

3)依据请求确认(也就是部分是你的Application_AuthenticateRequest) - 检查,看是否有cookie存在,如果是这样,得到了用户的身份和角色,并设置HttpContext.Current.User

3) Per Request Validation (the part that is is your Application_AuthenticateRequest) - check to see if a cookie exists, and if so, get the user's Identity and Roles and set HttpContext.Current.User.

通常情况下,FormsAuthentication模块隐藏了大部分这个从你的。它看起来像你的code尝试使用一些FormAuthentication的元素(如的FormsAuthenticationTicket和FormsIdentity,这是罚款,只要你得到你想要的东西。

Typically, the FormsAuthentication module hides most of this from you. It looks like your code is trying to use some of the elements of FormAuthentication (like the FormsAuthenticationTicket and FormsIdentity. This is fine as long as you get what you want.

您Login_Authenticate方法,除非你正在设置上的cookie到期看起来不错。这将使如果关闭并重新打开浏览器cookie的坚持,即使。因为这不是你想要的行为,我不会设置一个cookie过期。设置这就像选中记住我复选框。

Your Login_Authenticate method looks fine EXCEPT you are setting an expiration on the cookie. This will make the cookie persist even if you close and reopen the browser. Since this is not the behavior you want, I would not set a cookie expiration. Setting this is like checking the "remember me" checkbox.

在Application_AuthenticateRequest的code被运行的每个页面从您的应用程序服务的时间。它的主要任务是设置HttpContext.Current.User。通常情况下,如果没有用户登录,用户要么是空或匿名用户。如果用户登录,这应该重新present用户。

The code in Application_AuthenticateRequest gets run every time a page is served from your application. It's primary job is to set HttpContext.Current.User. Typically, if no user is logged in, User is either null or an Anonymous user. If a user is logged in, this should represent your user.

如果你正在做这三样东西,然后在code任何地方,你可以参考HttpContext.Current.User决定要显示什么级别的信息。举例来说,如果你想限制一个页面只有管理员,你可以称之为HttpContext.Current.Users.IsInRole(管理员),并从页面重定向他们离开,如果调用返回false。

If you are doing these three things, then anywhere in your code you can reference HttpContext.Current.User to decide what level of information you want to display. For instance, if you want to restrict a page to administrators only, you could call HttpContext.Current.Users.IsInRole("Administrators"), and redirect them away from the page if the call returns false.

希望这有助于。

这篇关于窗体身份验证理解context.user.identity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆