Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Security and hardening

RestSharp sends the OAuth2 access token but the API answers access denied

Error401 Unauthorized

Short answer

When curl succeeds with the same token, the header RestSharp builds is wrong. OAuth2AuthorizationRequestHeaderAuthenticator writes the scheme OAuth unless you pass Bearer, it never removes a Bearer prefix you already added, and an authenticator keeps the token it was given. Use JwtAuthenticator or pass Bearer, and refresh the token in place.

  • Applies to RestSharp 114, .NET 8, .NET 9
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Send the same token with curl using the scheme the standard defines. If curl is accepted and RestSharp is denied, the token is fine and the difference is the Authorization header that RestSharp builds.

    curl -i -H "Authorization: Bearer $TOKEN" https://api.example.com/me
  2. 2Match what you see, then jump to its fix

    1. 1curl with Bearer is accepted, and the code creates new OAuth2AuthorizationRequestHeaderAuthenticator(token) with one argument.The OAuth2 header authenticator sends the scheme OAuth, not BearerFix
    2. 2The token was copied from a header or a token response field that already includes the word Bearer, and the code passes it to OAuth2AuthorizationRequestHeaderAuthenticator with Bearer as the type.The token string already starts with Bearer, so the header says it twiceFix
    3. 3Calls succeed for a while after start-up, then every call is denied until the process restarts.The authenticator keeps sending the token it was created with, after that token expiredFix

What does the error look like?

  • 401 Unauthorized
  • Access denied
  • WWW-Authenticate: Bearer error="invalid_token"

Cause 1 of 3

The OAuth2 header authenticator sends the scheme OAuth, not Bearer

1Check

The class takes a second argument, the token type, and its default is OAuth. The header value it builds is the token type, a space and the token, so the default sends OAuth followed by your token, while the standard scheme for access tokens is Bearer.

grep -rn "OAuth2AuthorizationRequestHeaderAuthenticator" --include=*.cs .

2Fix

Pass Bearer as the token type, or use JwtAuthenticator, which writes the Bearer value itself.

var authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(token, "Bearer");
var options = new RestClientOptions("https://api.example.com") { Authenticator = authenticator };
var client = new RestClient(options);

// or, equivalent for bearer tokens:
// Authenticator = new JwtAuthenticator(token)

3Verify

The same request that was denied now returns a success status.

var response = await client.ExecuteAsync(new RestRequest("/me"));
Console.WriteLine(response.StatusCode);

Confirmed by restsharp.dev

Did this fix it?

Cause 2 of 3

The token string already starts with Bearer, so the header says it twice

1Check

OAuth2AuthorizationRequestHeaderAuthenticator always puts the token type in front of the string you give it and does not look at what is inside, so a token that begins with Bearer produces Bearer Bearer and then the token.

Console.WriteLine(token.StartsWith("Bearer ", StringComparison.Ordinal));

2Fix

Hand the authenticator the raw token only, or switch to JwtAuthenticator: it adds the Bearer prefix only when the string does not already start with it.

var raw = token.StartsWith("Bearer ", StringComparison.Ordinal) ? token["Bearer ".Length..] : token;
var options = new RestClientOptions("https://api.example.com")
{
    Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(raw, "Bearer")
};

3Verify

The check prints False for the value you pass in, and the request is accepted.

Console.WriteLine(raw.StartsWith("Bearer ", StringComparison.Ordinal));

Confirmed by github.com

Did this fix it?

Cause 3 of 3

The authenticator keeps sending the token it was created with, after that token expired

1Check

The standard describes invalid_token as meaning the access token is expired, revoked, malformed or invalid for another reason, and says the answer is HTTP 401. If the token is a JWT, its exp claim is a Unix time you can compare with the clock.

echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null
date +%s

2Fix

Keep a reference to the JwtAuthenticator, and call SetBearerToken with the refreshed token. RestSharp's own page points to this method for refreshing.

var jwt = new JwtAuthenticator(token);
var client = new RestClient(new RestClientOptions("https://api.example.com") { Authenticator = jwt });

// after you obtained a new access token from the identity provider
jwt.SetBearerToken(newToken);

3Verify

A call made after the refresh returns a success status instead of 401.

var response = await client.ExecuteAsync(new RestRequest("/me"));
Console.WriteLine(response.StatusCode);

Confirmed by restsharp.dev

Did this fix it?

How do I stop it coming back?

  • Build the RestClient in one place and let that code own the token, so a refresh has one home.
  • On every denied call, log the status code and the WWW-Authenticate header: its error value says whether the token is expired or malformed.
  • Prove each new integration with curl first, then compare the header RestSharp sends.
  • Never put access tokens in source files or logs.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Security

A valid JWT fails to decode because its segments are base64url, not base64

Convert.FromBase64String throws FormatException on a JWT segment

A JWT is three base64url segments joined by dots, and a standard base64 decoder refuses all three differences: base64url uses - and _ instead of + and /, leaves off the = padding, and the dots are not part of any base64 alphabet.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.