ASP.NET Core MVC with Identity - ArgumentNullException: Value cannot be null. (Parameter 'value') on signInManager.PasswordSignInAsync

Alexander J 20 Reputation points
2023-03-17T13:35:56.4266667+00:00

What's up everyone, I've been having this issue when implementing Identity authentication to my app.

This is the error I get:

ArgumentNullException: Value cannot be null. (Parameter 'value')
System.ArgumentNullException.Throw(string paramName)
System.ArgumentNullException.ThrowIfNull(object argument, string paramName)
System.Security.Claims.Claim..ctor(string type, string value, string valueType, string issuer, string originalIssuer, ClaimsIdentity subject, string propertyKey, string propertyValue)
System.Security.Claims.Claim..ctor(string type, string value)
Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory<TUser>.GenerateClaimsAsync(TUser user)
Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory<TUser, TRole>.GenerateClaimsAsync(TUser user)
Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory<TUser>.CreateAsync(TUser user)
Microsoft.AspNetCore.Identity.SignInManager<TUser>.CreateUserPrincipalAsync(TUser user)
Microsoft.AspNetCore.Identity.SignInManager<TUser>.SignInWithClaimsAsync(TUser user, AuthenticationProperties authenticationProperties, IEnumerable<Claim> additionalClaims)
Microsoft.AspNetCore.Identity.SignInManager<TUser>.SignInOrTwoFactorAsync(TUser user, bool isPersistent, string loginProvider, bool bypassTwoFactor)
Microsoft.AspNetCore.Identity.SignInManager<TUser>.PasswordSignInAsync(TUser user, string password, bool isPersistent, bool lockoutOnFailure)
Microsoft.AspNetCore.Identity.SignInManager<TUser>.PasswordSignInAsync(string userName, string password, bool isPersistent, bool lockoutOnFailure)
MyApp.Areas.Identity.Pages.Account.LoginModel.OnPostAsync(string returnUrl) in Login.cshtml.cs
+
                var result = await _signInManager.PasswordSignInAsync(user.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);

And here's the code:

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            var user = new MyAppUser { UserName = Input.Username };
            returnUrl ??= Url.Content("~/");

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            if (ModelState.IsValid)
            {
                Console.WriteLine(user.UserName);
                // 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(user.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return LocalRedirect(returnUrl);
                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }

I'm really scratching my head here. When I enter a wrong password, it errors out saying it's an invalid login, but when I enter the correct password it just gives me the "Value cannot be blank" error. Also, it works fine when I register.

(I used the scaffolding tool to set up Identity, by the way)

Developer technologies ASP.NET ASP.NET Core
Developer technologies .NET Other
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2023-03-25T12:24:37.87+00:00

    I updated the AspNetUsers table to match your record.

    UPDATE [dbo].[AspNetUsers]
    SET [Email] = NULL,
    	[NormalizedEmail] = NULL,
    	[EmailConfirmed] = 0
    

    This causes the login to fail with "User account not allowed." The IsNotAllowed flag in Identity is set to true.

    The default Identity Razor Pages use an email address as the username and email address. Clearly, you've made some changes to the source code. While I can't reproduce the null parameter exception, I assume the error is coming from changes that you've made somewhere in the code base.

    I would troubleshoot PostgreSQL and your code changes. Create a new project, wire up PostgreSQL, and scaffold Identity. Do not update the source code. Then create an account and try to login. If your able to login then there is a problem with the your source code changes.

    If you get the same null value error then I suspect an issue with the PostgreSQL provider and the Identity API. Submit feedback by clicking the "Submit Feedback" button in the upper right corner of Visual Studio. Provide enough information to reproduce the error.


3 additional answers

Sort by: Most helpful
  1. Erkan Sahin 840 Reputation points
    2023-03-25T12:27:19.46+00:00

    The ArgumentNullException: Value cannot be null error on signInManager.PasswordSignInAsync indicates that one of the parameters passed to the method is null.

    To solve this issue, you can try the following steps:

    1. Check the signInManager parameter to make sure it is not null. If it is null, make sure you have initialized it properly.
    2. Check the email and password parameters to make sure they are not null. If either one is null, you can throw an exception or return an error message to the user.
    3. If the email and password parameters are not null, make sure that the user with the given email exists in the system. You can use the userManager.FindByEmailAsync method to find the user by email.
    4. If the user exists, use the signInManager.PasswordSignInAsync method to sign in the user. Make sure you are passing the correct parameters to the method. The first parameter should be the user object, the second parameter should be the password, and the third parameter should be a boolean value indicating whether to remember the user's login.
    5. If the sign-in is successful, redirect the user to the desired page. If it fails, return an error message to the user.

    Here is an example code snippet that demonstrates how to use signInManager.PasswordSignInAsync method:

    var user = await userManager.FindByEmailAsync(email);
    if (user != null)
    {
        var result = await signInManager.PasswordSignInAsync(user, password, false, false);
        if (result.Succeeded)
        {
            // Redirect the user to the desired page
        }
        else if (result.IsLockedOut)
        {
            // Handle locked-out user
        }
        else if (result.RequiresTwoFactor)
        {
            // Handle two-factor authentication
        }
        else
        {
            // Handle invalid login attempt
        }
    }
    else
    {
        // Handle invalid email
    }
    

  2. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-03-25T17:12:40.4766667+00:00

    As the error is from the role provider, I assume there is some issue there. If you are using the default database role provider, I’d check the roles tables for valid values.

    0 comments No comments

  3. Alexander J 20 Reputation points
    2023-03-26T10:22:32.9733333+00:00

    I got it working guys. Turns out I specified UserName in my app's IdentityUser class, which of course didn't work 🤦‍♂️I feel so dumb.

    Thank you all for helping out!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.