'Checking for User in LDAP server, working fine in my local but not working in IIS server

    /// <summary>
    /// Authenticates the user against LDAP Server with system credentials
    /// </summary>
    /// <returns></returns>

    [HttpGet]
    public JsonResult AuthenticationResult()
    {
        Thread.GetDomain().SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
        WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;
        // or, if you're in Asp.Net with windows authentication you can use:
        // WindowsPrincipal principal = (WindowsPrincipal)User;
        string distinguishedName = string.Empty;
        string emailId = string.Empty;
        string samAccountName = string.Empty;
        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
        {
            UserPrincipal up = UserPrincipal.FindByIdentity(pc, principal.Identity.Name);
            distinguishedName = up.DistinguishedName;
            emailId = up.EmailAddress;
            samAccountName = up.SamAccountName;
        }
    
        var IsUserFoundInLdap = _ldapAuthenticationService.IsUserFoundInLdap(distinguishedName, emailId, samAccountName);
        if (IsUserFoundInLdap)
        {
            var isUserExistinDB = _context.EiEbUsers.Where(x => x.EMAIL_ID == emailId && x.ADMIN_ROLE == 1);
            if (isUserExistinDB != null && isUserExistinDB.Count() > 0)
            {
                 return Json("Admin");
            }
            else
            {
                return Json("Not an Admin");
            }
        }
        else
        {
            return Json("user not found in LDAP Server");
        }
    }
    
    
    
    public bool IsUserFoundInLdap(string distinguishedName, string emailId, string samAccountName)
    {
        DirectoryEntry entry = null;
        bool userfound = false;
        try
        {
            // Entry to agency and checkes the agency to look for specific agency group
            if (distinguishedName.Contains("(ITS)", StringComparison.OrdinalIgnoreCase))
            {
                entry = new DirectoryEntry(eiEbLdapConnection.ITSPath, eiEbLdapConnection.DirectoryUserName, eiEbLdapConnection.DirectoryPassword);
            }
            if (distinguishedName.Contains("(DOT)", StringComparison.OrdinalIgnoreCase))
            {
                entry = new DirectoryEntry(eiEbLdapConnection.DOTPath, eiEbLdapConnection.DirectoryUserName, eiEbLdapConnection.DirectoryPassword);
            }
    
            //directory checking for name, mail, userlogged details in the ldap
            //string[] loadProps = new string[] { "cn", "mail", "samaccountname", "name" };
            string[] loadProps = new string[] { "mail" };
            //using (var srch = new DirectorySearcher(entry, "(|(ObjectClass=user)(ObjectClass=group)(ObjectClass=Person)(samaccountname=*)(mail=*))", loadProps))
            using (var srch = new DirectorySearcher(entry, "(|(ObjectClass=user)(ObjectClass=group)(ObjectClass=Person)(mail='" + emailId + "'))", loadProps))
            {
                srch.PageSize = 5000;
                srch.SearchScope = SearchScope.Subtree;
                //srch.ServerTimeLimit = new TimeSpan(50000);
                srch.Filter = "(|(ObjectClass=user)(ObjectClass=group)(ObjectClass=Person)(mail='" + emailId + "'))";
                //srch.Filter = "(|(ObjectClass=user)(ObjectClass=group)(ObjectClass=Person)(samaccountname=*)(mail='" + emailId + "'))";
                SearchResultCollection results = srch.FindAll();
    
                // authenticating the user based on email if user found in the agency then user is authenticated.
                foreach (SearchResult profile in results)
                {
                    if (profile.Properties["mail"] != null && profile.Properties["mail"].Count > 0)
                    {
                        if (string.Equals(profile.Properties["mail"][0].ToString(), emailId, StringComparison.OrdinalIgnoreCase))
                        {
                            userfound = true;
                            break;
                        }
                    }
                }
                results.Dispose();
            };
            return userfound;
        }
        catch (Exception ex)
        {
                    throw ex;
        }
        finally
        {
            entry.Close();
            entry.Dispose();
        }  
    }

Error is below:

Category: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware EventId: 1 SpanId: d4e8ef289e939740 TraceId: 921af4faaa578f43bbab2f36975b4c95 ParentId: 0000000000000000 RequestId: 8000061e-0000-fd00-b63f-84710c7967bb RequestPath: /EiEbDocuments/AuthenticationResultAn unhandled exception has occurred while executing the request.Exception: System.NullReferenceException: Object reference not set to an instance of an object. at testdbcontext.Models.LdapAuthenticationService.IsUserFoundInLdap(String distinguishedName, String emailId, String samAccountName) in C:\Users\UBuddi\OneDrive - New York State Office of Information Technology Services\Downloads\testdbcontext 05-03-2022\testdbcontext\testdbcontext\Models\Authentication\LdapAuthenticationService.cs:line 67 at testdbcontext.Controllers.EiEbDocumentsController.AuthenticationResult() in C:\Users\UBuddi\OneDrive - New York State Office of Information Technology Services\Downloads\testdbcontext 05-03-2022\testdbcontext\testdbcontext\Controllers\EiEbDocumentsController.cs:line 113 at lambda_method32(Closure , Object , Object[] ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source