'ArgumentNullException: String reference not set to an instance of a String. Parameter name: s System.Text.Encoding.GetBytes(string s)

I have this method to generate token:

[HttpPost("login")]
        public async Task<IActionResult> login(UserForLoginDto userForLoginDto)
        {
            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

            if(userFromRepo == null)
               return Unauthorized();

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            };   

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return Ok(new{
                token = tokenHandler.WriteToken(token)
            });

        }

When I call this API via postman :

localhost:5000/api/auth/login

In body username: "john", password: "password"

I got this error:

An unhandled exception occurred while processing the request. ArgumentNullException: String reference not set to an instance of a String. Parameter name: s System.Text.Encoding.GetBytes(string s)

because of this line :

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

Kindly help to fix this error.



Solution 1:[1]

For this error, it seems _config.GetSection("AppSettings:Token").Value return null.

For _config.GetSection("AppSettings:Token"), you need to make sure your appsettings.json contains content below:

{
"AppSettings": {
    "Token": "This is Token"
},   
}

Solution 2:[2]

I got this exact error, I am using VS Code. I solved this issue by setting an environment variable called "tokenkey" this can be set in the terminal using the following:

dotnet user-secrets set "TokenKey" "super secret key" -p API/

my code below

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenKey"]));

if you are getting this error in production mode you will have to set the environment variable on your server.

Solution 3:[3]

I got this same error. I solved this issue by setting environment variable in my launch settings.json file, you could put yours in the appsettings.json file, just make sure it contians like the sample code below

"environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development",
    "JWT_SECRET": "This is a secret or key for jwt",
    "JWT_ISSUER": "Auth"
  }

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Edward
Solution 2 Dharman
Solution 3 Olabode Olaniyi David