1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HttpClientをDIで使い回したはいいが、認証が通らない

Posted at

ChatGPTに聞いたこと

テストを行っているが認証が通らない。認証情報は確かにログイン時に HttpClient に登録している。

ChatGPTの答え

DIから取得した HttpClient のライフサイクルは Transient であるため、認証情報を別の場所で設定しても保持されない。
そのため、認証情報を付与するには DelegatingHandler を継承したクラスを作成し、SendAsync() をオーバーライドするのが適切である。

設定方法

リクエスト送信前に認証ヘッダーを付与してしまう、という仕組みです。以下はトークン認証の例ですが、もちろん Basic 認証などにも応用可能です。

public class AuthDelegatingHandler : DelegatingHandler
{
    private readonly ITokenService _tokenService;
    public AuthDelegatingHandler(ITokenService tokenService) =>
        _tokenService = tokenService;

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var token = await _tokenService.GetAccessTokenAsync();
        request.Headers.Authorization =
            new AuthenticationHeaderValue("Bearer", token);
        return await base.SendAsync(request, cancellationToken);
    }
}

サービス登録時にハンドラーを組み込みます。

services
  .AddHttpClient<WebRelayClient>(client =>
  {
      client.BaseAddress = new Uri("https://xxxxxxx.xx.xx");
  })
  .AddHttpMessageHandler<AuthDelegatingHandler>();

こうすることで、呼び出す際に必ず認証情報が付与されるようになります。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?