【问题标题】:Can't seem to authenticate a request to my ASP.NET Core API似乎无法验证对我的 ASP.NET Core API 的请求
【发布时间】:2022-01-03 11:43:32
【问题描述】:

我有一个本地 API 正在为我的项目运行,我在其中编写了一个方法来获取当前登录用户的个人资料数据,如下所示:

[HttpGet("profile"), Authorize]
public async Task<ActionResult> GetProfile()
{
    var claim = HttpContext.User.Claims.First(o => o.Type == "id");
    var usr = _userVerification.GetUser(int.Parse(claim.Value));
    return new OkObjectResult(new GenericAPIResponse<ProfileVM>(new ProfileVM()
    {
        FirstName = usr.FirstName,
        Id = usr.UserId,
        LastName = usr.LastName,
        Role = (ProfileVM.RoleType)usr.Role
    }));
}

在 API 项目中,我配置了 JWT 身份验证,并通过 Authorization 标头传递令牌以“登录”。当我通过提琴手手动执行此操作时,一切正常,但是每当我尝试从客户端应用程序调用它时,它就永远不想出于某种未知原因将该标头放入请求中。

在我的客户中,我终于接受了 RestSharp 的这种方法:

if (bearer != null)
    client.Authenticator = new JwtAuthenticator(bearer);
...
public async Task<GenericAPIResponse<ProfileVM>> GetUserProfile()
{
    var req = new RestRequest("/user/profile");
    //req.AddHeader("Authorization", $"Bearer {bearer}"); <- tried that as well but no luck
    var res = await client.ExecuteAsync(req);
    return JsonConvert.DeserializeObject<GenericAPIResponse<ProfileVM>>(res.Content);        
}

现在的问题是我总是收到 401 错误,因为 AUTHORIZATION 标头永远不会包含在请求中。我之前也厌倦了 Refit,因为我做了这样的方法声明:

Task<GenericAPIResponse<ProfileVM>> GetProfile([Header("Authorization")] string token);

什么都没有。似乎无论我做什么,我都无法在我的请求中添加授权标头,而使用 Refit 添加任何其他 X- 标头就可以了。

这是上面带有 RestSharp 的代码的结果(从 Fiddler4 复制):

GET https://localhost:44355/api/user/profile HTTP/1.1
Host: localhost:44355
Accept: application/json, text/json, text/x-json, text/javascript, application/xml, text/xml
User-Agent: RestSharp/106.15.0.0
Connection: Keep-Alive
Accept-Encoding: gzip, deflate

我正式没有想法并开始兜圈子。我在这里想念什么?请问我可以在这里获得一些新的观点吗?

【问题讨论】:

  • 您是否配置了鉴权服务?如果它丢失了,那可能会导致它跳过标题。
  • 是的,我有,除非我错过了一些重要的东西,但我不这么认为,因为当手动发送请求时,身份验证工作正常。

标签: c# .net rest asp.net-core restsharp


【解决方案1】:

RestRequest 只是一个带有精美涂层的HttpRequest,所以我总是添加一个像这样的不记名令牌标头,将它添加到我将其交给HttpClientHttpRequestMessage 对象为我处理。

var request = new HttpRequestMessage(HttpMethod.Get, myFullUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

var response = await this.httpClient.SendAsync(request, cancellationToken);

更新

要使用 RestSharp 的本机功能执行此操作,您需要执行此操作。

client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", bearerToken));

这个想法是您对RestClient 本身进行身份验证,而不是将身份验证添加到每个 Rest 请求中。

【讨论】:

    猜你喜欢
    • 2019-08-03
    • 2013-04-08
    • 1970-01-01
    • 2011-04-17
    • 2015-10-12
    • 2021-07-28
    • 2022-11-14
    • 1970-01-01
    • 2019-03-27
    相关资源
    最近更新 更多