【发布时间】:2021-12-23 07:52:49
【问题描述】:
我有一个正在运行的 Web API,我尝试从中获取不记名令牌。从 Postman 开始的请求正在工作,我取回了令牌。从我的应用程序执行后,我总是会收到 http 400 Bad Request 错误。
我在这里错过了什么?
public async Task<string> GetToken(string userName, string passWord)
{
var request = new HttpRequestMessage(HttpMethod.Post, "api/auth/login");
request.Headers.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{ userName}:{ passWord}")));
request.Headers.Host = "api.my-host.com";
request.Headers.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
using var responseStream = await response.Content.ReadAsStreamAsync();
var authResult = await JsonSerializer.DeserializeAsync<AuthResult>(responseStream);
return authResult == null ? "" : authResult.Access_Token;
}
根据要求,这里是 Postman 结果的屏幕截图:
我创建了一个 HttpGet 请求,并在代码中添加了来自 Postman 的不记名令牌,然后我收到了数据。只是令牌请求好像有问题。
还有我的控制器:
namespace AmsAPI.Controller
{
[Produces("application/json")]
[Route("api/auth")]
[ApiController]
[Authorize]
public class AuthenticationController : ControllerBase
{
private readonly IAuthenticationManager _authenticationManager;
public AuthenticationController(IAuthenticationManager authenticationManager)
{
_authenticationManager = authenticationManager;
}
[HttpPost("login"), AllowAnonymous]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public async Task<ActionResult> Login([FromHeader] byte[] basic)
{
if (!ModelState.IsValid) return BadRequest();
string Basic = Encoding.UTF8.GetString(basic);
var splitBasic = Basic.Split(':');
AuthCredentials credentials = new()
{
UserName = splitBasic[0],
Password = splitBasic[1]
};
return await _authenticationManager.SignInCheck(credentials) ?
Ok(new
{
message = string.Format("User {0} successfully logged in.", credentials.UserName),
access_token = await _authenticationManager.CreateToken(),
token_type = "bearer",
expires_in = "3600"
}) :
Unauthorized();
}
[HttpGet("user")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public async Task<List<User>> GetUser() => await _authenticationManager.GetUser();
}
}
【问题讨论】:
-
请尝试通过邮递员请求令牌,并将结果显示给我们。我们需要检查这个http请求的内容吗?
-
共享您的完整控制器?您的控制器是否允许
annonymous请求?令牌控制器应该允许匿名请求。 -
那么 Postman 也无法工作...控制器有
annonymous请求 -
您能否添加完整的控制器类,但仍不清楚问题所在
-
这是完整的控制器。不知道你在找什么? Postman从控制器收到正确的数据,但是客户端总是收到Bad Request错误,不知道为什么?
标签: asp.net-core http-headers dotnet-httpclient webapi bearer-token