【发布时间】:2021-08-23 02:30:52
【问题描述】:
我有这种方法可以使用 c# .netcore 3.1 版本生成 jwt 令牌。
[HttpPost]
public async Task<IActionResult> CreateToken([FromBody] LoginViewModel model)
{
if( ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Username);
if (user != null)
{
var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
if (result.Succeeded)
{
// Create the token
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_config["Tokens:Issuer"],
_config["Tokens:Audience"],
claims,
signingCredentials: creds,
expires: DateTime.UtcNow.AddMinutes(30));
var results = new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
};
return Created("", results);
}
}
}
return BadRequest();
}
}
当我通过邮递员调用 CreateToken 方法 API 时:
When I call this API via postman :
http://localhost:8888/account/CreateToken
我收到了这个错误
System.ArgumentNullException: String reference not set to an instance of a String. (Parameter 's')
at System.Text.Encoding.GetBytes(String s)
at DutchTreat.Contollers.AccountController.CreateToken(LoginViewModel model) in E:\.NET Core and Angular\DutchTreat\Contollers\AccountController.cs:line 101
经过一些调试,我发现错误来了,因为这条线
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
这是我使用的配置文件
{
"Color": {
"Favourite": "Blue"
},
"ConnectionStrings": {
"DutchContextDb": "Data Source=(localdb)\\ProjectsV13;Initial Catalog=DutchTreatDb;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"DutchTreat": "Information",
"Microsoft": "Warning"
},
"Tokens": {
"Key": "a;sdlkfja; lsdkfj ;alksdfj ;alksdfj; aiefj;lskij;flds",
"Issuer": "http://localhost:8888",
"Audience": "http://localhost:8888"
}
}
}
请帮助解决此错误
【问题讨论】:
标签: c# asp.net-core jwt postman rest