I have implemented my own custom IAuthenticator
called OAuth2BearerAuthenticator
which basically takes in a ClientId
and ClientSecret
and before any request is made, it checks if it has a valid Bearer Token - if not it will use the client credentials to go away and "Refresh" the token before proceeding with the original request.
The Authenticate
method of this custom authenticator contains the following:
public void Authenticate(IRestClient client, IRestRequest request)
{
if (!bearerTokenExpiration.HasValue || bearerTokenExpiration.Value < DateTime.Now)
{
RefreshBearerToken();
}
if (request.Parameters.Any(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)))
{
return;
}
request.AddHeader("Authorization", string.Format("Bearer {0}", bearerToken));
}
I have verified that the bearer token that it is generating is valid - I can successfully request data from the API I am trying to access with the same bearer token authorization header in DHC (Chrome REST extension)
I have also verified that it is not returning early from the if (any authorization paramaters)
statement.
However, RestSharp is failing with the response "HTTP Basic: Access denied.\n"
I don't know if it is relevant but the response also contains a WWW-Authenticate
header with the value Basic realm=\"Web Password\"
Any help is much appreciated. Thanks.
I think if you are are using bearer token to authenticate your request you can use this way:
client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", bearerToken));
Hope it work!