我正在尝试使用API验证用户,由于某种原因,此代码(在using语句内)将空用户名和密码传递给控制器。我在控制器上放置了停止点,就在using语句之前,用户名和密码正确地进入,直到using语句。一旦我们传递了它,在控制器中,传入的参数为null。
HttpResponseMessage response = await _httpClient.PostAsync("http://localhost:5063/api/authentication/authenticate",
(new StringContent(JsonConvert.SerializeObject(formData), Encoding.UTF8, "application/json")))
客户端的全部代码:
public async Task<AuthenticatedUser> 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<string, string> ("grant_type", "password"),
new KeyValuePair<string, string> ("username", username ),
new KeyValuePair<string, string> ("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<AuthenticatedUser>();
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<string> 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<Claim>();
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; }
}
任何帮助都非常感谢!
我做了以下更改,他们解决了我的错误:首先在客户端修改身份验证方法,如下所示:
public async Task<AuthenticatedUser> Authenticate(string username, string password) // task essentially returning void for async method, it returns a task, saying we are waiting to finish
{
// we have to send FormUrlEncodedContent for the username/password and the type
// this will create the user data that we will send to the API Endpoint (authentication)
var formData = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string> ("grant_type", "password"),
new KeyValuePair<string, string> ("username", username ),
new KeyValuePair<string, string> ("password", password )
});
using (HttpResponseMessage response = await _httpClient.PostAsync("http://localhost:5063/api/authentication/authenticate",formData))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<AuthenticatedUser>();
return result;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
也,我修改了我的控制器动作接收[FromForm]而不是[FromBody]
public ActionResult<string> Authenticate([FromForm] AuthenticationRequestBody request)
现在我的客户端能够在身份验证后从API接收令牌。由于