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)
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)
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.