Skip to content

Commit b041656

Browse files
committed
avoid rebuilding the Basic Authentication header for each request
The username and password never change, so there is no need to re-encode them in Base64 for each request. We can juste compute the header value once and reuse it to save time.
1 parent 6d3ef35 commit b041656

File tree

1 file changed

+4
-8
lines changed

1 file changed

+4
-8
lines changed

RestSharp/Authenticators/HttpBasicAuthenticator.cs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,12 @@ namespace RestSharp
2222
{
2323
public class HttpBasicAuthenticator : IAuthenticator
2424
{
25-
private readonly string _username;
26-
private readonly string _password;
25+
private readonly string _authHeader;
2726

2827
public HttpBasicAuthenticator(string username, string password)
2928
{
30-
_password = password;
31-
_username = username;
29+
var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password)));
30+
_authHeader = string.Format("Basic {0}", token);
3231
}
3332

3433
public void Authenticate(IRestClient client, IRestRequest request)
@@ -43,10 +42,7 @@ public void Authenticate(IRestClient client, IRestRequest request)
4342
// only add the Authorization parameter if it hasn't been added by a previous Execute
4443
if (!request.Parameters.Any(p => p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)))
4544
{
46-
var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", _username, _password)));
47-
var authHeader = string.Format("Basic {0}", token);
48-
49-
request.AddParameter("Authorization", authHeader, ParameterType.HttpHeader);
45+
request.AddParameter("Authorization", _authHeader, ParameterType.HttpHeader);
5046
}
5147
}
5248
}

0 commit comments

Comments
 (0)