RestSharp OAuth2 Bearer Authentication Failing With Access Denied

30,468

Solution 1

Also, for Bearer token you can use one of the existing authenticators:

client.Authenticator = new JwtAuthenticator(yourAccessToken);

Or:

client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(yourAccessToken, "Bearer");

Solution 2

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!

Share:
30,468
Tom Glenn
Author by

Tom Glenn

A UK based web & software developer specializing in .NET and PHP.

Updated on July 09, 2022

Comments

  • Tom Glenn
    Tom Glenn almost 2 years

    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.