Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestSharp OAuth2 Bearer Authentication Failing With Access Denied

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.

like image 826
Tom Glenn Avatar asked Apr 27 '15 10:04

Tom Glenn


2 Answers

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

client.Authenticator = new JwtAuthenticator(yourAccessToken);

Or:

client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(yourAccessToken, "Bearer");
like image 72
Gennadii Kurabko Avatar answered Nov 18 '22 12:11

Gennadii Kurabko


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!

like image 26
Vipin Sharma Avatar answered Nov 18 '22 11:11

Vipin Sharma