Click here to Skip to main content
15,905,148 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hi Team

I need some help, current issue my web form username is null. I think what i want to achieve, we are using our own domain server. My approach want this web app to be able to authenticate me as a user and be redirected to dashboard. For now i am acting as an Administrator. The application is not doing this and im trying to get an idea, as to why my username is null but redirected back to Login

What I have tried:

<system.web>
  <compilation debug="true" targetFramework="4.7.2"/>
  <httpRuntime targetFramework="4.7.2"/>
    <sessionState mode="InProc" />
</system.web>
<runtime>


C#
<pre><appSettings>
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    <!---Adding some active directory here for configuration- -->
    <add key="DomainName" value="ROCKLANDS"/>
    <add key="DomainController" value="LDAP://ROCKLANDS"/>
	  
  </appSettings>


//controller
C#
<pre> [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel login)
        {
            if (ModelState.IsValid)
            {
                // validate credentials via AD Account
                bool isAuthenticated = ValidateCredentials(login.UserName, login.Password);

                if (isAuthenticated)
                {
                    // Set the "Username" session variable
                    Session["Username"] = login.UserName;

                    // return successful, redirect to the dashboard.
                    TempData["SuccessMessage"] = "Login successful!";
                    return RedirectToAction("Dashboard", "Account");
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password");
                }
            }
            return View(login);
        }


        // validate user account from AD(Active Directory) .
        private bool ValidateCredentials(string password, string username)
        {
            // validate credentials against AD Account.
            using(PrincipalContext pc = new PrincipalContext(ContextType.Domain))
            {
                return pc.ValidateCredentials(username, password);
            }
        }

        //GET: GetLoggedInUser.
       
        public JsonResult GetLoggedInUser()
        {
            // fetch the logged in user's username.
            string username = User.Identity.Name;
            return Json(new { Username = username }, JsonRequestBehavior.AllowGet);
        }

        // dashboard for the account: Performed by HR Manager and Administrators


        public ActionResult Dashboard()
        {
            // retrieve user information from the session.
            var username = Session["Username"] as string;
            if (string.IsNullOrEmpty(username))
            {
                // Redirect to login if username is null or empty
                return RedirectToAction("Login", "Account");
            }

            // Proceed with dashboard logic
            var imageUrl = GetImageUrl(username);
            var userModel = new UserModel { UserName = username, ImageUrl = imageUrl };
            return View(userModel);
        }



        private string GetImageUrl(string username)
        {
            // connect to Active Directory and fetch user's image.
            using (var principalContext = new PrincipalContext(ContextType.Domain))
            {
                using (var user = UserPrincipal.FindByIdentity(principalContext, username))
                {
                    if (user != null)
                    {
                        // check if the user has a thumbnail photo.
                        if (user.GetUnderlyingObject() is DirectoryEntry directoryEntry && directoryEntry.Properties.Contains("thumbnailPhoto"))
                        {
                            byte[] thumnailBytes = directoryEntry.Properties["thumbnailPhoto"].Value as byte[];
                            if (thumnailBytes != null && thumnailBytes.Length > 0)
                            {
                                // convert the byte array to base64 string
                                string base64String = Convert.ToBase64String(thumnailBytes);
                                return "data:image/jpeg;base64," + base64String;
                            }
                        }
                    }
                }
            }
            return "http://intranet.rocklands.co.za/default-user-image.png";
        }

       
    }
Posted
Updated 8-Mar-24 0:08am
v2
Comments
Richard Deeming 8-Mar-24 7:05am    
Is there a reason you're not just using Windows authentication? That will be more secure than having your users re-type their AD credentials into your view.

1 solution

Your first issue is happening with this code -

C#
return pc.ValidateCredentials(username, password);


No credentials were found, returning a 'NULL' value.
The second part then, based on the NULL value is -

C#
// Redirect to login if username is null or empty
                return RedirectToAction("Login", "Account");


This will return you back to your Login form. So, start looking at why no Credentials were returned and your issue will be resolved.

Richard is also spot on, use Windows Authentication - C# using Windows authentication to login in to app[^]
 
Share this answer
 
Comments
Gcobani Mkontwana 11-Mar-24 2:55am    
Andre, thanks i notice and link gave me clear understanding. Rather use Windows Authentication for security reason.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900