【发布时间】:2018-09-24 19:49:07
【问题描述】:
您好,我在使用 Net Core 创建令牌时感到困惑,我已按照指南进行操作,但在 Postman 中执行 Post 请求时无法正常工作。
看,我的数据库有 ef 核心迁移,我的 User 类有 UserName 和 Password {get;set;}。
然后我创建了一个包含以下内容的 AuthController:
public class AuthController : Controller
{
private readonly IConfiguration _configuration;
private readonly HacsysContext _context;
public AuthController(IConfiguration configuration, HacsysContext context) {
_configuration = configuration;
}
[AllowAnonymous]
[HttpPost]
[Route("token")]
public IActionResult Post([FromBody]Personal personal)
{
if (ModelState.IsValid)
{
var userId = GetUserIdFromCredentials(personal);
if (userId == -1)
{
return Unauthorized();
}
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, personal.CorreoE),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken
(
issuer: _configuration["Issuer"],
audience: _configuration["Audience"],
claims: claims,
expires: DateTime.UtcNow.AddDays(10),
notBefore: DateTime.UtcNow,
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SigningKey"])),
SecurityAlgorithms.HmacSha256)
);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
}
return BadRequest();
}
private int GetUserIdFromCredentials(Personal personal)
{
var userId = -1;
var email = personal.CorreoE;
var password = personal.Contrasena;
if (personal.CorreoE.Equals(email))
{
userId = 1;
}
return userId;
}
}
基本上,当我在 GetUserIdFromCredentials 中比较电子邮件是否等于 peronal 时。CorreoE 总是返回 True,即使在 Postman 中我发送的 POST 中只有一个字母或不同的电子邮件或不在我的数据库中的不同电子邮件。
【问题讨论】:
标签: asp.net-core jwt entity-framework-core