Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change how ReCaptchaService consumes HttpClient #14544

Merged
merged 3 commits into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static IServiceCollection AddReCaptcha(this IServiceCollection services,
{
// c.f. https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests
services.AddScoped<ReCaptchaService>()
.AddHttpClient<ReCaptchaService>()
.AddHttpClient(nameof(ReCaptchaService))
.AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(0.5 * attempt)));

services.AddSingleton<IDetectRobots, IPAddressRobotDetector>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,23 @@ public class ReCaptchaService
};

private readonly ReCaptchaSettings _reCaptchaSettings;
private readonly HttpClient _httpClient;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IEnumerable<IDetectRobots> _robotDetectors;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILogger _logger;
protected readonly IStringLocalizer S;
private HttpClient _httpClient;

public ReCaptchaService(
HttpClient httpClient,
IHttpClientFactory httpClientFactory,
IOptions<ReCaptchaSettings> optionsAccessor,
IEnumerable<IDetectRobots> robotDetectors,
IHttpContextAccessor httpContextAccessor,
ILogger<ReCaptchaService> logger,
IStringLocalizer<ReCaptchaService> stringLocalizer)
{
_httpClientFactory = httpClientFactory;
_reCaptchaSettings = optionsAccessor.Value;
_httpClient = httpClient;
_robotDetectors = robotDetectors;
_httpContextAccessor = httpContextAccessor;
_logger = logger;
Expand Down Expand Up @@ -123,6 +124,7 @@ private async Task<bool> VerifyAsync(string responseToken)
{ "response", responseToken }
});

_httpClient ??= _httpClientFactory.CreateClient(nameof(ReCaptchaService));
var response = await _httpClient.PostAsync($"{_reCaptchaSettings.ReCaptchaApiUri.TrimEnd('/')}/siteverify", content);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<ReCaptchaResponse>(_jsonSerializerOptions);
Expand Down