Hi Team
I want to find out some examples, i am building Asp.net MVC using C# on 4.7.net framework. Using Identity without authentication on Windows, but using Active Directory, e.g As an Administrator during form registration i must be prompt dynamically with my username from AD account, then redirect to the dashboard(View.cshtml) where i can perform CRUD operation for new users. Are there any examples i can relate i want to accomplish something along this line for our in house project.

Jayraj ChhayaRank #304 · 8.2K reputationPosted Mar 8, 2024, 2:38 AM EST
To achieve user identity integration with Active Directory in an ASP.NET MVC application, you can leverage Windows Authentication and the
System.DirectoryServices.AccountManagementnamespace in C#. Here's a high-level overview of the steps involved:PrincipalContextto interact with Active Directory for user information.While there might not be a specific example that matches your exact requirements, you can refer to Microsoft's documentation on Windows Authentication in ASP.NET and the
System.DirectoryServices.AccountManagementnamespace for guidance. Additionally, you can adapt and customize existing examples to suit your specific needs for the in-house project.Guest UserRank #877 · 2.5K reputationPosted Mar 8, 2024, 3:53 AM EST
Hi Jaraj
Let me share my current logic, because i am now getting 401 Unauthorized. Maybe i am missing something, username and password are correct i am using them for our AD account.
// web.config
// controller //GET:Login public ActionResult Login() { return View(); } //POST: Login [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(LoginModel login) { if(ModelState.IsValid) { // validate credits via AD Account bool isAuthenticated = ValidateCredentials(login.UserName, login.Password); if(isAuthenticated) { // return successful, redirect to the dashboard. TempData["SuccessMessage"] = "Login successful!"; return RedirectToAction("Dashboard", "Home"); }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. [Authorize(Roles = "Admin")] public JsonResult GetLoggedInUser() { // fetch the logged in user's username. string username = User.Identity.Name; return Json(new { Username = username }, JsonRequestBehavior.AllowGet); } // view.cshmtl @model CVResumeScanning.Models.LoginModel @{ ViewBag.Title = "Login Home Page"; } @using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "loginForm" })) { @Html.AntiForgeryToken() @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "col-md-4 col-form-label text-md-right" }) @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" }) @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "col-md-4 col-form-label text-md-right" }) @Html.PasswordFor(model => model.Password, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" }) Login } $(document).ready(function () { $('#loginForm').submit(function (e) { e.preventDefault(); // Prevent default form submission // Check for empty fields var username = $('#UserName').val().trim(); var password = $('#Password').val().trim(); if (!username || !password) { // Display error message for empty fields $('.alert').remove(); // Remove any existing alerts $('Please enter both username and password. ').insertBefore('#loginForm'); return; } // Perform server-side validation $.ajax({ url: '@Url.Action("GetLoggedInUser", "Account")', type: 'GET', data: $(this).serialize(), success: function (response) { // If the login was successful, display a Bootstrap alert message $('.alert').remove(); // Remove any existing alerts $('Login successful! ').insertBefore('#loginForm'); // Redirect to the dashboard after a short delay setTimeout(function () { window.location.href = '@Url.Action("Dashboard", "Home")'; }, 2000); // 2000 milliseconds (2 seconds) }, error: function (xhr) { // If there are errors, replace the form with the returned HTML $('#loginForm').replaceWith(xhr.responseText); } }); }); });