Skip to content

Commit

Permalink
Merge branch 'refs/heads/dev' into swallow-content-dispose-exception
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeyzimarev committed May 26, 2024
2 parents 2439bc5 + fd392c9 commit c13a00d
Show file tree
Hide file tree
Showing 26 changed files with 346 additions and 1,842 deletions.
19 changes: 0 additions & 19 deletions SECURITY.md

This file was deleted.

64 changes: 55 additions & 9 deletions docs/docs/advanced/authenticators.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ var request = new RestRequest("/api/users/me") {
var response = await client.ExecuteAsync(request, cancellationToken);
```

## Basic Authentication
## Basic authentication

The `HttpBasicAuthenticator` allows you pass a username and password as a basic `Authorization` header using a base64 encoded string.

Expand All @@ -36,43 +36,89 @@ var client = new RestClient(options);
## OAuth1

For OAuth1 authentication the `OAuth1Authenticator` class provides static methods to help generate an OAuth authenticator.
OAuth1 authenticator will add the necessary OAuth parameters to the request, including signature.

The authenticator will use `HMAC SHA1` to create a signature by default.
Each static function to create the authenticator allows you to override the default and use another method to generate the signature.

### Request token

Getting a temporary request token is the usual first step in the 3-legged OAuth1 flow.
Use `OAuth1Authenticator.ForRequestToken` function to get the request token authenticator.
This method requires a `consumerKey` and `consumerSecret` to authenticate.

```csharp
var options = new RestClientOptions("https://example.com") {
var options = new RestClientOptions("https://api.twitter.com") {
Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret)
};
var client = new RestClient(options);
var request = new RestRequest("oauth/request_token");
```

The response should contain the token and the token secret, which can then be used to complete the authorization process.
If you need to provide the callback URL, assign the `CallbackUrl` property of the authenticator to the callback destination.

### Access token

This method retrieves an access token when provided `consumerKey`, `consumerSecret`, `oauthToken`, and `oauthTokenSecret`.
Getting an access token is the usual third step in the 3-legged OAuth1 flow.
This method retrieves an access token when provided `consumerKey`, `consumerSecret`, `oauthToken`, and `oauthTokenSecret`.
If you don't have a token for this call, you need to make a call to get the request token as described above.

```csharp
var authenticator = OAuth1Authenticator.ForAccessToken(
consumerKey, consumerSecret, oauthToken, oauthTokenSecret
);
var options = new RestClientOptions("https://example.com") {
var options = new RestClientOptions("https://api.twitter.com") {
Authenticator = authenticator
};
var client = new RestClient(options);
var request = new RestRequest("oauth/access_token");
```

If the second step in 3-leg OAuth1 flow returned a verifier value, you can use another overload of `ForAccessToken`:

```csharp
var authenticator = OAuth1Authenticator.ForAccessToken(
consumerKey, consumerSecret, oauthToken, oauthTokenSecret, verifier
);
```

This method also includes an optional parameter to specify the `OAuthSignatureMethod`.
The response should contain the access token that can be used to make calls to protected resources.

For refreshing access tokens, use one of the two overloads of `ForAccessToken` that accept `sessionHandle`.

### Protected resource

When the access token is available, use `ForProtectedResource` function to get the authenticator for accessing protected resources.

```csharp
var authenticator = OAuth1Authenticator.ForAccessToken(
consumerKey, consumerSecret, oauthToken, oauthTokenSecret,
OAuthSignatureMethod.PlainText
consumerKey, consumerSecret, accessToken, accessTokenSecret
);
var options = new RestClientOptions("https://api.twitter.com/1.1") {
Authenticator = authenticator
};
var client = new RestClient(options);
var request = new RestRequest("statuses/update.json", Method.Post)
.AddParameter("status", "Hello Ladies + Gentlemen, a signed OAuth request!")
.AddParameter("include_entities", "true");
```

### xAuth

xAuth is a simplified version of OAuth1. It allows sending the username and password as `x_auth_username` and `x_auth_password` request parameters and directly get the access token. xAuth is not widely supported, but RestSharp still allows using it.

Create an xAuth authenticator using `OAuth1Authenticator.ForClientAuthentication` function:

```csharp
var authenticator = OAuth1Authenticator.ForClientAuthentication(
consumerKey, consumerSecret, username, password
);
```

### 0-legged OAuth

The same access token authenticator can be used in 0-legged OAuth scenarios by providing `null` for the `consumerSecret`.
The access token authenticator can be used in 0-legged OAuth scenarios by providing `null` for the `consumerSecret`.

```csharp
var authenticator = OAuth1Authenticator.ForAccessToken(
Expand Down Expand Up @@ -120,7 +166,7 @@ For each request, it will add an `Authorization` header with the value `Bearer <

As you might need to refresh the token from, you can use the `SetBearerToken` method to update the token.

## Custom Authenticator
## Custom authenticator

You can write your own implementation by implementing `IAuthenticator` and
registering it with your RestClient:
Expand Down
25 changes: 12 additions & 13 deletions docs/docs/advanced/serialization.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,24 +126,23 @@ Here is an example of a custom serializer that uses `System.Text.Json`:

```csharp
public class SimpleJsonSerializer : IRestSerializer {
public string Serialize(object obj) => JsonSerializer.Serialize(obj);
public string? Serialize(object? obj) => obj == null ? null : JsonSerializer.Serialize(obj);

public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);
public string? Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);

public T Deserialize<T>(IRestResponse response) => JsonSerializer.Deserialize<T>(response.Content);
public T? Deserialize<T>(RestResponse response) => JsonSerializer.Deserialize<T>(response.Content!);

public string[] SupportedContentTypes { get; } = {
"application/json", "text/json", "text/x-json", "text/javascript", "*+json"
};
public ContentType ContentType { get; set; } = ContentType.Json;

public string ContentType { get; set; } = "application/json";

public DataFormat DataFormat { get; } = DataFormat.Json;
public ISerializer Serializer => this;
public IDeserializer Deserializer => this;
public DataFormat DataFormat => DataFormat.Json;
public string[] AcceptedContentTypes => ContentType.JsonAccept;
public SupportsContentType SupportsContentType
=> contentType => contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase);
}
```

The value of the `SupportedContentTypes` property will be used to match the
serializer with the response `Content-Type` headers.
The `SupportedContentTypes` function will be used to check if the serializer is able to deserialize the response based on the `Content-Type` response header.

The `ContentType` property will be used when making a request so the
server knows how to handle the payload.
The `ContentType` property will be used when making a request so the server knows how to handle the payload.
4 changes: 2 additions & 2 deletions docs/docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ Only the most important or breaking changes are listed there. All other changes

* Added [interceptors](advanced/interceptors.md).
* As interceptors provide a better way to interject the request and response execution flow, request properties `OnBeforeRequest`, `OnBeforeDeserialization` and `OnAfterRequest` are marked obsolete and will be removed in future versions.
* Client option `MaxTimeout` renamed to `Timeout` and changed type to `Timespan` for clarity. It doesn't configure the `HttpClient` timeout any more. Instead, the same method is used for client and request level timeouts with cancellation tokens.
* Request option `Timeout` changed type to `Timespan` for clarity.
* **Breaking change.** Client option `MaxTimeout` renamed to `Timeout` and changed type to `Timespan` for clarity. It doesn't configure the `HttpClient` timeout anymore. Instead, the same method is used for client and request level timeouts with cancellation tokens.
* **Breaking change.** Request option `Timeout` changed type to `Timespan` for clarity.
* Added .NET 8 target.
* Support uploading files as content without multipart form.
* Added `CacheControl` options to client and requests.
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/usage/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ If you need to override the property name or format, you can do it using the `Re
```csharp
public class RequestModel {
// override the name and the format
[RequestAttribute(Name = "from_date", Format = "d")]
[RequestProperty(Name = "from_date", Format = "d")]
public DateTime FromDate { get; set; }
}

Expand Down
9 changes: 0 additions & 9 deletions package.json

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ namespace RestSharp.Authenticators;
/// UTF-8 is used by default but some servers might expect ISO-8859-1 encoding.
/// </remarks>
[PublicAPI]
public class HttpBasicAuth(string username, string password, Encoding encoding)
public class HttpBasicAuthenticator(string username, string password, Encoding encoding)
: AuthenticatorBase(GetHeader(username, password, encoding)) {
public HttpBasicAuth(string username, string password) : this(username, password, Encoding.UTF8) { }
public HttpBasicAuthenticator(string username, string password) : this(username, password, Encoding.UTF8) { }

static string GetHeader(string username, string password, Encoding encoding)
=> Convert.ToBase64String(encoding.GetBytes($"{username}:{password}"));
Expand Down
Loading

0 comments on commit c13a00d

Please sign in to comment.