Search code examples
c#restoauthaccess-tokenrestsharp

OAuth 2 authentication with RESTSHARP doesn't work


I am trying to use Restsharp (version 105, also tried newest 106) to connect to REST API. Method of authentication is OAuth 2

I get a token from authentication service but I have trouble using it. Output request always skips the Authorization parameter.

Request should include parameter like Authorization: Bearer token1235

POST /wares/ HTTP/1.1

HTTP headers:
Accept: application/json
User-Agent: RestSharp/105.0.1.0
Host: localhost
Authorization: Bearer token1235
Accept-Encoding: gzip, deflate

Request body:

But the authorization line in the request is skipped every time. I tried various ways, but was completely unsuccessful. Restsharp is manipulating the parameters, which I assign. How to include the Authorization parameter with bearer token in the header? A guess it must be pretty standard procedure.

I tried many possibilities suggested in another threads with similar problem but wasn't successfull at all. For example I would expect one of these should work but it doesn't :

  1. client.Authenticator = new OAuth2UriQueryParameterAuthenticator(AccessToken); // this does write 'oauth_token=token12345' text in request body but that's it

  2. request.AddParameter("Authorization", "Bearer " + AccessToken, ParameterType.HttpHeader); // this does include nothing in the request, there is no parameter at all

  3. request.AddHeader("Authorization","Bearer " + AccessToken); // this does include nothing in the request, there is no parameter at all


Solution

  • According to the format that you expect, you want to use JWT.

    The way to do it with RestSharp is:

    client.Authenticator = new JwtAuthenticator(accessToken);
    

    This authenticator produces the authorisation header you want:

    Authorization: Bearer {accessToken}