Hello Microsoft Team,
When i try to login by username and password.
null exception error occur when controller hit opt.TokenValidationParameters = new TokenValidationParameters() which is available in startup.cs .
opt.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
Errors is
Exception has occurred: CLR/System.ArgumentNullException
An exception of type 'System.ArgumentNullException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'String reference not set to an instance of a String.'
at System.Text.Encoding.GetBytes(String s)
at CI.API.Startup.<ConfigureServices>b__4_4(JwtBearerOptions opt) in D:\MyProject\CI.API\Startup.cs:line 67
at Microsoft.Extensions.Options.ConfigureNamedOptions`1.Configure(String name, TOptions options)
at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
at Microsoft.Extensions.Options.OptionsMonitor`1.<>c__DisplayClass11_0.<Get>b__0()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
In startup.cs
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
In appsettings.json
"AppSettings":{"Token":"hey i am here"
}
AuthController
[HttpPost("login")]
public async Task<IActionResult> Login(LoginViewModel model)
{
var user = await _userManager.FindByNameAsync(model.UserName);
var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
if (!result.Succeeded)
{
return BadRequest(result);
}
return Ok(new
{
result = result,
token = await JwtTokenGenerator(user)
});
}
public async Task<string> JwtTokenGenerator(User userInfo)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier,userInfo.Id),
new Claim(ClaimTypes.Name,userInfo.UserName)
};
var roles = await _userManager.GetRolesAsync(userInfo);
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var securityKey = new SymmetricSecurityKey(Encoding.ASCII
.GetBytes(_config.GetSection("AppSettings:Token").Value));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(1),
SigningCredentials = credentials
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}