ASP.NET MVC: Get user id of currently logged in user

16,123

Solved the problem by following this link: howto get the user id from a FormsAuthentication page in asp.net MVC? posted by https://stackoverflow.com/users/2516718/derloopkat

The System.Web.HttpContext.Current.User.Identity.Name Function returns the "name" attribute in the Authentication Ticket, which in my case was the email address. I then got the User ID by having a query to the Users database.

db.Users.Where(x => x.Email == System.Web.HttpContext.Current.User.Identity.Name).FirstOrDefault().ID;

Thanks for everybody's help.


Update in 2020: The query can be simplified to:

db.Users.FirstOrDefault(x => x.Email == System.Web.HttpContext.Current.User.Identity.Name).ID;

Share:
16,123
mneumann
Author by

mneumann

Updated on June 04, 2022

Comments

  • mneumann
    mneumann almost 2 years

    I am new to ASP.NET MVC and am trying to create a web app.

    The problem I have is that in the controller class I need to get the UserID of the current user, but I am very confused about how one would do that. Also, it seems that the user is not authenticated after logging in, because if I use the [Authorize] annotation it throws an HTTP Error 401.0 - Unauthorized error.

    This is my Authentication.cs class:

    public static class Authentication
    {
        public static bool CreateNewTicket(User user, bool rememberMe)
        {
    
            try
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    user.Email,
                    DateTime.Now,
                    DateTime.Now.AddDays(5),
                    rememberMe,
                    user.ID.ToString(),
                    FormsAuthentication.FormsCookiePath
                    );
    
                string encryptedTicket = FormsAuthentication.Encrypt(ticket);
    
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                cookie.HttpOnly = true;
                if (!HttpContext.Current.Request.IsLocal)
                    cookie.Secure = true;
    
                HttpContext.Current.Response.Cookies.Add(cookie);
    
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static bool AuthUser(string Email, string Password)
        {
            using (var db = new AntContext())
            {
                string password = Password;
                string email = Email;
    
                string hashedPW = GetHash(password);
    
                bool userValid = db.Users.Any(user => user.Email == email && user.Password == hashedPW);
    
                if (userValid)
                {
                    var actUser = db.Users.FirstOrDefault(u => u.Email == Email && u.Password == hashedPW);
    
                    if (!actUser.IsLocked)
                    {
                        if (CreateNewTicket(actUser, false))
                        {
    
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else if (actUser.IsLocked)
                    {
    
    
    
                    }
                }
                return false;
    
            }
        }
    

    The actual problem happens when I try to store data in a database.

    [HttpPost]
        public ActionResult Q_FirstPage(ViewModels.Q1_Answer_VM vm)
        {
            vm.Qst = new Models.Questionnaire();
            vm.Qst.NumericAnswers = new List<Models.NumericAnswer>();
            vm.Qst.TextAnswers = new List<Models.TextAnswer>();
            vm.Qst.IsComplete = false;
            vm.Qst.StartedOn = DateTime.Now;
            vm.Qst.NumericAnswers.Add(vm.Breite);
            vm.Qst.NumericAnswers.Add(vm.Tiefe);
            vm.Qst.NumericAnswers.Add(vm.Hoehe);
            vm.Qst.TextAnswers.Add(vm.Sonstiges);
    
            //vm.qst.User_ID = 22; if I set the User ID manually, it works
    
            db.Questionnaires.Add(vm.Qst);
            db.SaveChanges();
    
            return View();
        }
    

    The Viewmodel works fine and returns the data input, but the UserID is null. The data table "Questionnaire" uses the UserID as a foreign key, which makes it throw an error when it comes to the savedata() part because I guess it expects the correct UserID. So I guess I need to get the current UserID, pass it to the instantiated object which is then passed to the data context and then saved into the database.

    Unfortunately, I find it very hard to find complete information about how user authentication works in ASP.NET.

    If you need more information, please let me know.

    This is my Login method:

     [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(Login_VM login_vm)
        {
            if (!ModelState.IsValid)
            {
                return View(login_vm);
            }
    
            if (Authentication.AuthUser(login_vm.Email, login_vm.Password) == true && (login_vm.Email != null || login_vm.Password != null))
            {
    
                Classes.Authentication.CreateNewTicket(login_vm.usr, true);
                return RedirectToAction("Login");
            }
    
            else
                return View("~/Views/Home/Index.cshtml");
        }
    

    And this is my registration method:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AddUser(User model)
    // add new User to db
    {
    
        if (ModelState.IsValid)
        {
            User usr = new Models.User();
            usr = model;
            model.Password = Authentication.GetHash(model.Password);
            db.Users.Add(model);
            db.SaveChanges();
        }
        return View();
    }