RestSharp sends the OAuth2 access token but the API answers access denied
401 UnauthorizedShort 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.
Fix it fast
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/me2Match what you see, then jump to its fix
- 1
curl 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
The 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
Calls 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
- 1
What does the error look like?
401 UnauthorizedAccess deniedWWW-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
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
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 +%s2Fix
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
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
An ASP.NET Core API answers 401 with Bearer error="invalid_token"
401 Unauthorized
invalid_token in the WWW-Authenticate header means the access token is expired, revoked, malformed or invalid for another reason.
3 causes, each with a fixSecurity
ASP.NET Core cannot create the JWT because the signing key is too short or unusable
IDX10630: The '<key type>' for signing cannot be smaller than '<bits>' bits. KeySize: '<bits>'.
The error happens while the API signs the token, not while it checks one.
3 causes, each with a fixSecurity
.NET cannot convert the string to a JwtSecurityToken
SecurityTokenMalformedException
The handler only accepts a compact JWT: three dot-separated base64url segments for a signed token.
3 causes, each with a fixSecurity
AuthenticationException: your certificate validation callback returned false
System.Security.Authentication.AuthenticationException
This message means a validation callback was installed, yours or one a library added, and it returned false.
3 causes, each with a fixSecurity
DelegateAuthenticationProvider no longer exists in the Microsoft Graph .NET SDK
The type or namespace name 'DelegateAuthenticationProvider' could not be found
Microsoft Graph .NET SDK v5 removed DelegateAuthenticationProvider.
3 causes, each with a fixSecurity
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