RestSharp: Unable to reassign the Authenticator property in v109

Describe the bug The changes introduced by making the Authenticator on RestClient immutable makes it impossible to use the same RestClient for authentication and after successfully authentication setting the Authenticator for further method calls which require the client to be authenticated.

To Reproduce

internal sealed class CustomRestClient : IDisposable
{
  private readonly RestClient _restClient;

  public CustomRestClient(string baseUrl) => _restClient = new RestClient(baseUrl);  

  public void Dispose() => _restClient.Dispose();

  public async Task<bool> Authenticate(string clientId, string clientSecret)
  {
    RestRequest request = new RestRequest("api/oauth2/token");
    request.AddParameter("grant_type", "client_credentials");
    request.AddParameter("client_id", clientId);
    request.AddParameter("client_secret", clientSecret);
  
    AppOAuthToken? response = await _restClient.PostAsync<AppOAuthToken>(request);
    _restClient.Authenticator = response != null && response.AccessToken != null ? new JwtAuthenticator(response.AccessToken) : default;
  
    return response != null && response.AccessToken != null;
  }
}

Expected behavior The docs state that a single instance of RestClient should be used to prevent starvation.

Desktop (please complete the following information):

  • OS: Windows 10 21H2
  • .NET 7
  • Version 109.0.1

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 17 (4 by maintainers)

Most upvoted comments

Additionally, the RestSharp request object has an Authenticator property that you can override the RestClient Options Authenticator property value for any request that needs to use a differing Authenticator from the default.

Given how complex and fractured the authentication space is I think the only easy addition would be to add some assistance to the supplied Authenticator for 401 handling for expired/revoked tokens. Maybe something like this: (pseudo-code)

       <inside Execute method>:
       If response status is 401:
           if request included an auth header value: 
                add some additional state to pass to .Authenticate call to hint that it might be a re-auth (either due to expiration, or token revocation, the cause really isn't important of course)
                if the returned token is different:
                    re-execute the same url with the new token from the authenticator
                else: 
                     nothing else to do, let the caller deal with the problem

Determining if the request has an auth header could be done a couple of different ways if more than just ‘Authorization’ needs to be supported.