Skip to content

Commit cb436f2

Browse files
committed
Fixes #1677
1 parent c8c8342 commit cb436f2

File tree

5 files changed

+65
-80
lines changed

5 files changed

+65
-80
lines changed

src/RestSharp/Authenticators/OAuth2/OAuth2AuthorizationRequestHeaderAuthenticator.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,7 @@ public class OAuth2AuthorizationRequestHeaderAuthenticator : AuthenticatorBase {
2727
/// Initializes a new instance of the <see cref="OAuth2AuthorizationRequestHeaderAuthenticator" /> class.
2828
/// </summary>
2929
/// <param name="accessToken">The access token.</param>
30-
public OAuth2AuthorizationRequestHeaderAuthenticator(string accessToken)
31-
: this(accessToken, "OAuth") { }
30+
public OAuth2AuthorizationRequestHeaderAuthenticator(string accessToken) : this(accessToken, "OAuth") { }
3231

3332
/// <summary>
3433
/// Initializes a new instance of the <see cref="OAuth2AuthorizationRequestHeaderAuthenticator" /> class.
@@ -38,5 +37,5 @@ public OAuth2AuthorizationRequestHeaderAuthenticator(string accessToken)
3837
public OAuth2AuthorizationRequestHeaderAuthenticator(string accessToken, string tokenType) : base(accessToken) => _tokenType = tokenType;
3938

4039
protected override ValueTask<Parameter> GetAuthenticationParameter(string accessToken)
41-
=> new(new Parameter(KnownHeaders.Authorization, $"{_tokenType} {accessToken}", ParameterType.HttpHeader));
40+
=> new(new Parameter(KnownHeaders.Authorization, $"{_tokenType} {accessToken}", ParameterType.HttpHeader, false));
4241
}
Lines changed: 14 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,17 @@
11
using System.Net;
22
using RestSharp.IntegrationTests.Fixtures;
3-
using RestSharp.Tests.Shared.Extensions;
43
using RestSharp.Tests.Shared.Fixtures;
54

65
namespace RestSharp.IntegrationTests;
76

8-
public class AsyncTests : IAsyncLifetime {
7+
[Collection(nameof(TestServerCollection))]
8+
public class AsyncTests {
99
readonly ITestOutputHelper _output;
10-
readonly HttpServer _server;
10+
readonly RestClient _client;
1111

12-
public AsyncTests(ITestOutputHelper output) {
13-
_output = output;
14-
_server = new HttpServer(output);
15-
}
16-
17-
class ResponseHandler {
18-
void error(HttpListenerContext context) {
19-
context.Response.StatusCode = 400;
20-
context.Response.Headers.Add(KnownHeaders.ContentType, "application/xml");
21-
22-
context.Response.OutputStream.WriteStringUtf8(
23-
@"<?xml version=""1.0"" encoding=""utf-8"" ?>
24-
<Response>
25-
<Error>
26-
<Message>Not found!</Message>
27-
</Error>
28-
</Response>"
29-
);
30-
}
31-
32-
void success(HttpListenerContext context)
33-
=> context.Response.OutputStream.WriteStringUtf8(
34-
@"<?xml version=""1.0"" encoding=""utf-8"" ?>
35-
<Response>
36-
<Success>
37-
<Message>Works!</Message>
38-
</Success>
39-
</Response>"
40-
);
41-
42-
void timeout(HttpListenerContext context) => Thread.Sleep(1000);
12+
public AsyncTests(TestServerFixture fixture, ITestOutputHelper output) {
13+
_output = output;
14+
_client = new RestClient(fixture.Server.Url);
4315
}
4416

4517
class Response {
@@ -50,22 +22,20 @@ class Response {
5022
public async Task Can_Handle_Exception_Thrown_By_OnBeforeDeserialization_Handler() {
5123
const string exceptionMessage = "Thrown from OnBeforeDeserialization";
5224

53-
var client = new RestClient(_server.Url);
5425
var request = new RestRequest("success");
5526

5627
request.OnBeforeDeserialization += r => throw new Exception(exceptionMessage);
5728

58-
var response = await client.ExecuteAsync<Response>(request);
29+
var response = await _client.ExecuteAsync<Response>(request);
5930

6031
Assert.Equal(exceptionMessage, response.ErrorMessage);
6132
Assert.Equal(ResponseStatus.Error, response.ResponseStatus);
6233
}
6334

6435
[Fact]
6536
public async Task Can_Perform_ExecuteGetAsync_With_Response_Type() {
66-
var client = new RestClient(_server.Url);
6737
var request = new RestRequest("success");
68-
var response = await client.ExecuteAsync<Response>(request);
38+
var response = await _client.ExecuteAsync<Response>(request);
6939

7040
response.StatusCode.Should().Be(200);
7141
response.Data!.Message.Should().Be("Works!");
@@ -75,61 +45,50 @@ public async Task Can_Perform_ExecuteGetAsync_With_Response_Type() {
7545
public async Task Can_Perform_GET_Async() {
7646
const string val = "Basic async test";
7747

78-
var client = new RestClient(_server.Url);
7948
var request = new RestRequest($"echo?msg={val}");
8049

81-
var response = await client.ExecuteAsync(request);
50+
var response = await _client.ExecuteAsync(request);
8251
response.Content.Should().Be(val);
8352
}
8453

8554
[Fact]
8655
public async Task Can_Timeout_GET_Async() {
87-
var client = new RestClient(_server.Url);
88-
var request = new RestRequest("timeout", Method.Get).AddBody("Body_Content");
56+
var request = new RestRequest("timeout").AddBody("Body_Content");
8957

9058
// Half the value of ResponseHandler.Timeout
9159
request.Timeout = 200;
9260

93-
var response = await client.ExecuteAsync(request);
61+
var response = await _client.ExecuteAsync(request);
9462

9563
Assert.Equal(ResponseStatus.TimedOut, response.ResponseStatus);
9664
}
9765

9866
[Fact]
9967
public async Task Can_Timeout_PUT_Async() {
100-
using var server = SimpleServer.Create(Handlers.Generic<ResponseHandler>());
101-
102-
var client = new RestClient(server.Url);
10368
var request = new RestRequest("timeout", Method.Put).AddBody("Body_Content");
10469

10570
// Half the value of ResponseHandler.Timeout
10671
request.Timeout = 200;
10772

108-
var response = await client.ExecuteAsync(request);
73+
var response = await _client.ExecuteAsync(request);
10974

11075
Assert.Equal(ResponseStatus.TimedOut, response.ResponseStatus);
11176
}
11277

11378
[Fact]
11479
public async Task Handles_GET_Request_Errors_Async() {
115-
var client = new RestClient(_server.Url);
11680
var request = new RestRequest("status?code=404");
117-
var response = await client.ExecuteAsync(request);
81+
var response = await _client.ExecuteAsync(request);
11882

11983
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
12084
}
12185

12286
[Fact]
12387
public async Task Handles_GET_Request_Errors_Async_With_Response_Type() {
124-
var client = new RestClient(_server.Url);
12588
var request = new RestRequest("status?code=404");
126-
var response = await client.ExecuteAsync<Response>(request);
89+
var response = await _client.ExecuteAsync<Response>(request);
12790

12891
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
12992
Assert.Null(response.Data);
13093
}
131-
132-
public Task InitializeAsync() => _server.Start();
133-
134-
public Task DisposeAsync() => _server.Stop();
13594
}
Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,26 @@
1-
using System.Net;
2-
using System.Text;
1+
using System.Text;
32
using System.Web;
43
using RestSharp.Authenticators;
54
using RestSharp.IntegrationTests.Fixtures;
6-
using RestSharp.Tests.Shared.Extensions;
75

86
namespace RestSharp.IntegrationTests.Authentication;
97

8+
[Collection(nameof(TestServerCollection))]
109
public class AuthenticationTests {
10+
readonly TestServerFixture _fixture;
1111
readonly ITestOutputHelper _output;
1212

13-
public AuthenticationTests(ITestOutputHelper output) => _output = output;
14-
15-
static void UsernamePasswordEchoHandler(HttpListenerContext context) {
16-
var header = context.Request.Headers["Authorization"]!;
17-
18-
var parts = Encoding.ASCII
19-
.GetString(Convert.FromBase64String(header["Basic ".Length..]))
20-
.Split(':');
21-
22-
context.Response.OutputStream.WriteStringUtf8(string.Join("|", parts));
13+
public AuthenticationTests(TestServerFixture fixture, ITestOutputHelper output) {
14+
_fixture = fixture;
15+
_output = output;
2316
}
2417

2518
[Fact]
2619
public async Task Can_Authenticate_With_Basic_Http_Auth() {
2720
const string userName = "testuser";
2821
const string password = "testpassword";
2922

30-
var server = new HttpServer();
31-
await server.Start();
32-
33-
var client = new RestClient(server.Url) {
23+
var client = new RestClient(_fixture.Server.Url) {
3424
Authenticator = new HttpBasicAuthenticator(userName, password)
3525
};
3626
var request = new RestRequest("headers");
@@ -40,10 +30,8 @@ public async Task Can_Authenticate_With_Basic_Http_Auth() {
4030
var auth = HttpUtility.UrlDecode(header.Value)["Basic ".Length..];
4131
var value = Convert.FromBase64String(auth);
4232
var parts = Encoding.UTF8.GetString(value).Split(':');
43-
33+
4434
parts[0].Should().Be(userName);
4535
parts[1].Should().Be(password);
46-
47-
await server.Stop();
4836
}
4937
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using RestSharp.Authenticators.OAuth2;
2+
using RestSharp.IntegrationTests.Fixtures;
3+
4+
namespace RestSharp.IntegrationTests.Authentication;
5+
6+
[Collection(nameof(TestServerCollection))]
7+
public class OAuth2Tests {
8+
readonly TestServerFixture _fixture;
9+
10+
public OAuth2Tests(TestServerFixture fixture) => _fixture = fixture;
11+
12+
[Fact]
13+
public async Task ShouldHaveProperHeader() {
14+
var client = new RestClient(_fixture.Server.Url);
15+
var auth = new OAuth2AuthorizationRequestHeaderAuthenticator("token", "Bearer");
16+
client.Authenticator = auth;
17+
18+
var response = await client.GetJsonAsync<TestServerResponse[]>("headers");
19+
var authHeader = response!.FirstOrDefault(x => x.Name == KnownHeaders.Authorization);
20+
21+
authHeader.Should().NotBeNull();
22+
authHeader!.Value.Should().Be("Bearer token");
23+
}
24+
}

test/RestSharp.IntegrationTests/Fixtures/TestServer.cs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,18 @@
55

66
namespace RestSharp.IntegrationTests.Fixtures;
77

8-
public class HttpServer {
8+
public class TestServerFixture : IAsyncLifetime {
9+
public HttpServer Server { get; } = new();
10+
11+
public Task InitializeAsync() => Server.Start();
12+
13+
public Task DisposeAsync() => Server.Stop();
14+
}
15+
16+
[CollectionDefinition(nameof(TestServerCollection))]
17+
public class TestServerCollection : ICollectionFixture<TestServerFixture> { }
18+
19+
public sealed class HttpServer {
920
readonly WebApplication _app;
1021

1122
const string Address = "http://localhost:5151";
@@ -21,6 +32,7 @@ public HttpServer(ITestOutputHelper output = null) {
2132
_app.MapGet("success", () => new TestResponse { Message = "Works!" });
2233
_app.MapGet("echo", (string msg) => msg);
2334
_app.MapGet("timeout", async () => await Task.Delay(2000));
35+
_app.MapPut("timeout", async () => await Task.Delay(2000));
2436
// ReSharper disable once ConvertClosureToMethodGroup
2537
_app.MapGet("status", (int code) => Results.StatusCode(code));
2638

@@ -36,7 +48,10 @@ IResult HandleHeaders(HttpContext ctx) {
3648

3749
public Task Start() => _app.StartAsync();
3850

39-
public Task Stop() => _app.StopAsync();
51+
public async Task Stop() {
52+
await _app.StopAsync();
53+
await _app.DisposeAsync();
54+
}
4055
}
4156

4257
public record TestServerResponse(string Name, string Value);

0 commit comments

Comments
 (0)