Я разместил точки остановки на контроллере и как раз перед этим оператор using, имя пользователя и пароль вводятся правильно вплоть до оператора using. как только мы его передаем, в контроллере входящие параметры становятся нулевыми.
Код: Выделить всё
HttpResponseMessage response = await _httpClient.PostAsync("http://localhost:5063/api/authentication/authenticate",
(new StringContent(JsonConvert.SerializeObject(formData), Encoding.UTF8, "application/json")))
Код: Выделить всё
public async Task Authenticate(string username, string password) // task essentially returning void for async method, it returns a task, saying we are waiting to finish
{
var formData = new FormUrlEncodedContent(
new[]
{
new KeyValuePair ("grant_type", "password"),
new KeyValuePair ("username", username ),
new KeyValuePair ("password", password )
});
using (HttpResponseMessage response = await _httpClient.PostAsync("http://localhost:5063/api/authentication/authenticate",
(new StringContent(JsonConvert.SerializeObject(formData), Encoding.UTF8, "application/json"))))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync();
return result;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
Код: Выделить всё
[Route("api/authentication")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly IConfiguration _configuration;
private readonly IUserRepository _userRepository;
public static Users user = new Users();
public AuthenticationController(IConfiguration configuration, IUserRepository userRepository)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_userRepository = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
}
[HttpPost("authenticate")]
public ActionResult Authenticate([FromBody] AuthenticationRequestBody request)
{
//Step1: validate the username/password
var user = _userRepository.ValidateUserCredentials(
request.UserName, request.Password);
if (user == null)
{
return Unauthorized();
}
// IdentityModel.Tokens
var securityKey = new SymmetricSecurityKey(
Encoding.ASCII.GetBytes(_configuration["Authentication:SecretKey"]));
var signingCredentials = new SigningCredentials(
securityKey, SecurityAlgorithms.HmacSha256);
var claimsInfo = new List();
claimsInfo.Add(new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()));
claimsInfo.Add(new Claim(ClaimTypes.GivenName, user.FirstName));
claimsInfo.Add(new Claim(ClaimTypes.Surname, user.LastName));
var jwtSecurityToken = new JwtSecurityToken(
_configuration["Authentication:Issuer"],
_configuration["Authentication:Audience"],
claimsInfo,
DateTime.UtcNow, // start time, cannot use token before this time
DateTime.UtcNow.AddHours(4), // end time, cannot use after this time
signingCredentials
);
// view token at jwt.io or https://www.jstoolset.com/
var userToken = new JwtSecurityTokenHandler()
.WriteToken(jwtSecurityToken);
return Ok(new {AccessToken = userToken});
}
}
public class AuthenticationRequestBody
{
public string? UserName { get; set; }
public string? Password { get; set; }
}
Подробнее здесь: https://stackoverflow.com/questions/759 ... sword-c-sh