aspnet / Identity

[Archived] ASP.NET Core Identity is the membership system for building ASP.NET Core web applications, including membership, login, and user data. Project moved to https://github.com/aspnet/AspNetCore
Apache License 2.0
1.96k stars 870 forks source link

ASP.NET Core application giving object reference not set to an instance of an object exception in production but works fine in development #1902

Closed chandu1507 closed 5 years ago

chandu1507 commented 6 years ago

Ours website is school management application built on Asp.Net Core 2.0. I've requirement to enable users to have multiple roles across different schools with same credentials.For that I used cookies to share identity(ASP.NET Core identity).But it works perfect in development environment but when I host it to azure I'm getting object reference not set to an instance of an object exception in production.

this is the error in log file.

 failfail: Microsoft.AspNetCore.Server.Kestrel[13]
 Connection id "0HLFNDU99T5DB", Request id "0HLFNDU99T5DB:00000001": An unhandled exception was thrown by the application.
 System.NullReferenceException: Object reference not set to an instance of an object.
    at Guru.Web.Controllers.AccountController.<Login>d__16.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.<Execute>d__0.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__10.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__13.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__23.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__18.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__16.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.<Invoke>d__5.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Session.SessionMiddleware.<Invoke>d__9.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at Microsoft.AspNetCore.Session.SessionMiddleware.<Invoke>d__9.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at IdentityServer4.Hosting.IdentityServerMiddleware.<Invoke>d__3.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__8.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at IdentityServer4.Hosting.BaseUrlMiddleware.<Invoke>d__3.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.<Invoke>d__7.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.<Invoke>d__13.MoveNext()
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.<ProcessRequests>d__186`1.MoveNext()
 info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]

When I remove these lines of code from startup.cs it works absolutely fine.

  services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromHours(1);
            options.Cookie.Domain = ".zipschool.com";
            options.Cookie.Name = "ZipSchoolSession";
        });

services.ConfigureApplicationCookie(options =>
        {
            options.Cookie.Name = ".AspNet.ZipschoolSharedCookie";
            options.Cookie.Domain = ".zipschool.com";

       });

.AddCookie(options =>
         {
             options.Cookie.Name = "zipcookie";
             options.Cookie.Domain = "zipschools.com";
             //options.Cookie.SameSite = SameSiteMode.Strict;
         });

This is the login method

 [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginInputModel model)
    {
        if (SessionState.TenantName.Equals(K_HOME) && model.IsHomeTenant)
        {
            //string[] homePasswordSkip = { "Password" };
            //foreach (var modelKey in ModelState.Keys)
            //{
            //    if (homePasswordSkip.Contains(modelKey))
            //    {
            //        ModelState[modelKey].Errors.Clear();
            //        ModelState[modelKey].ValidationState = ModelValidationState.Valid;
            //    }
            //}

            var url = HttpContext.Request.Host.Value;
            var identityUserId = _userManager.FindByEmailAsync(model.Email);

            var tenant = _tenantService.GetUserTenant(identityUserId.Result.Id);

            SessionState.TenantId = tenant.Id;
            SessionState.TenantName = tenant.Name;
            SessionState.EnvironmentType = tenant.EnvironmentType;
            SessionState.SchoolId = tenant.SchoolId;

            //session["LoginInput"] = 

            var newPath = url.Replace(K_HOME, tenant.Name);// + "/Home/Index";

            CCACrypto ccaCrypto = new CCACrypto();
            var rediredcturl = HttpContext.Request.Scheme + "://" + newPath + "/Nav/" + ccaCrypto.Encrypt(model.Email, "Guru");

            //return RedirectPermanent(rediredcturl);
            //TempData["LoginInput"] = model;

            return Redirect(rediredcturl);

        }
        if (ModelState.IsValid)
        {
            var identityUserId = _userManager.FindByEmailAsync(model.Email);

            var activity = false;
            if (identityUserId.Result != null)
            {
                activity = _tenantService.GetUserActivity(identityUserId.Result.Id, SessionState.TenantId);
            }
            if (!activity)
            {
                ViewBag.message = "You Are UnAuthorized";
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return View(await GetLoginViewModel(model));
            }
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set lockoutOnFailure: true
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberLogin, lockoutOnFailure: false);
            //var useractivity =  _guruDbContext.User.FirstOrDefault(x => x.Email == model.Email );

            if (result.Succeeded)
            {
                _logger.LogInformation(1, "User logged in.");

                return RedirectToLocal(model.Email, model.ReturnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToAction(nameof(SendCode), new { ReturnUrl = model.ReturnUrl, RememberMe = model.RememberLogin });
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning(2, "User account locked out.");
                return View("Lockout");
            }
            else
            {
                ApplicationUser au = await _userManager.FindByEmailAsync(model.Email);
                if (au.IsNull())
                {
                    ViewBag.CredentialError = "Account does not exist. Try using a valid email id OR create new account.";
                }
                else
                {
                    ViewBag.CredentialError = "Wrong user name or password.";
                }
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                //LoginViewModel loginViewModel = ;

                return View(await GetLoginViewModel(model));
            }
        }

        LoginViewModel loginViewModel = await GetLoginViewModel(model);
        // If we got this far, something failed, redisplay form
        return View(await GetLoginViewModel(model));
    }
blowdart commented 6 years ago

Where is the exception being thrown? During request processing? On login? In that stack trace I don't see anything from asp.net identity at all, only identity server, so this might be a question for them.

blowdart commented 5 years ago

We're closing this issue as no response or updates have been provided in a timely manner. If you have more details and are encountering this issue please add a new reply and re-open the issue.