简体   繁体   中英

Get ID of current logged in user in ASP.NET Web Forms

I want to get id of current loggedin user. I can get Username: User.Identity.Name . I have two tables Users and Reservations. UserID is a foreign key at Reservations table. I have build an function that return id of current logged-in user:

private Int32 ReturnUserID() {
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    con.Open();
    SqlCommand cmd = new SqlCommand("ReturnUserID", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlParameter p1 = new SqlParameter("Username", User.Identity.Name);
    cmd.Parameters.Add(p1);
    SqlDataReader rd = cmd.ExecuteReader();
    if (rd.Read()) {
        int u = Convert.ToInt12(rd["UserID"]);
        return u;
    } else return 0;

}

Please tell me a specific way that how can I get and store the id of the current loggedin user?

The tutorial you're using looks like it's relying on a FormsIdentity and a GenericPrincipal, so you can discover their properties through casting:

var p = (GenericPrincipal)HttpContext.Current.User;
var i = (FormsIdentity)HttpContext.Current.User.Identity;
//look for claims or whatever you use to store the ID

If you have a custom IIdentity or IPrincipal, then change the cast to use your custom type and get the ID property that way.

EDIT: One way to do what I'm suggesting is to take this line from the tutorial you mentioned:

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

...and instead of using a GenericPrincipal, create your own IPrincipal that also stores the user ID. This approach would require a round trip to the database with each request.

Alternatives are to store the user ID in session, which is secure, but consumes memory.

Lastly, you can store the ID in the UserData property of the FormsAuthenticationTicket (along with the roles). The forms authentication ticket is encrypted, but sent to the client. This approach is probably the best-performing overall and decently secure.

To go with that approach, you'd need to change this part of the tutorial code to include the ID:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 
  userName,
  DateTime.Now,
  DateTime.Now.AddMinutes(50),
  rememberUserName,
  roles + "@@@@" + userId, //<-******** This Line Changes ********
  FormsAuthentication.FormsCookiePath);

//... then in Application_AuthenticateRequest() do something like this:

var userData = ticket.UserData.Split(new string[]{"@@@@"}, StringSplitOptions.RemoveEmptyEntries);
var userIdAsString = userData[1];
var roles = userData[0].Split( new char[]{ ',' } ); 

If you are already using ASP.Net identity most straightforward way is to use user manager. Upon successful login, you can use the login model's email to retrieve the user object using the user manager's FindByEmail or FindByEmailAsync method. Further, if you want to find out the user's role then use can use the user manager's IsInRole role method by parsing the id of the user and the role name.

**** This code shows how to get the logged-in user at login.****

 protected void LogIn(object sender, EventArgs e)
 {
        if (IsValid)
        {
            // Validate the user password
            var userManager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();              

            // This doen't count login failures towards account lockout
            // To enable password failures to trigger lockout, change to shouldLockout: true
            var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

            switch (result)
            {
                case SignInStatus.Success:
              
                    //If login success find the user record by email using user manager
                    var user =  userManager.FindByEmail(Email.Text);        
                    
                    //Store logged in user in session
                    Session["CurrentUser"] = user;

                    //find out current user's role and save it in session
                    if(userManager.IsInRole(user.Id, "Admin"))
                    {
                        Session["CurrentUserRole"] = "Admin";
                    }
                    else
                    {
                        Session["CurrentUserRole"] = "Staff";
                    }

                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    break;
                case SignInStatus.LockedOut:
                    Response.Redirect("/Account/Lockout");
                    break;
                case SignInStatus.RequiresVerification:
                    Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",  Request.QueryString["ReturnUrl"],RememberMe.Checked),true);
                    break;
                case SignInStatus.Failure:
                default:
                    FailureText.Text = "Invalid login attempt";
                    ErrorMessage.Visible = true;
                    break;
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM