Skip to content

fix: Authentication Cookies follow redirects #305

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
## 4.1.0 [unreleased]

### Features
1. [#101](https://github.com/influxdata/influxdb-client-csharp/pull/304): Add `InvocableScriptsApi` to create, update, list, delete and invoke scripts by seamless way
1. [#304](https://github.com/influxdata/influxdb-client-csharp/pull/304): Add `InvocableScriptsApi` to create, update, list, delete and invoke scripts by seamless way

### Bug Fixes
1. [#305](https://github.com/influxdata/influxdb-client-csharp/pull/305): Authentication Cookies follow redirects

## 4.0.0 [2022-03-18]

Expand Down
40 changes: 40 additions & 0 deletions Client.Test/InfluxDbClientTest.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -283,6 +284,45 @@ public async Task RedirectToken()
anotherServer.Stop();
}

[Test]
public async Task RedirectCookie()
{
_client.Dispose();
_client = InfluxDBClientFactory.Create(new InfluxDBClientOptions.Builder()
.Url(MockServerUrl)
.Authenticate("my-username", "my-password".ToCharArray())
.AllowRedirects(true)
.Build());

var anotherServer = WireMockServer.Start(new WireMockServerSettings
{
UseSSL = false
});

// auth cookies
MockServer
.Given(Request.Create().UsingPost())
.RespondWith(Response.Create().WithHeader("Set-Cookie", "session=xyz"));

// redirect to another server
MockServer
.Given(Request.Create().UsingGet())
.RespondWith(Response.Create().WithStatusCode(301).WithHeader("location", anotherServer.Urls[0]));

// success response
anotherServer
.Given(Request.Create().UsingGet())
.RespondWith(CreateResponse("{\"status\":\"active\"}", "application/json"));

var authorization = await _client.GetAuthorizationsApi().FindAuthorizationByIdAsync("id");
Assert.AreEqual(AuthorizationUpdateRequest.StatusEnum.Active, authorization.Status);

Assert.AreEqual("xyz", MockServer.LogEntries.Last().RequestMessage.Cookies["session"]);
Assert.AreEqual("xyz", anotherServer.LogEntries.Last().RequestMessage.Cookies["session"]);

anotherServer.Stop();
}

[Test]
public async Task Anonymous()
{
Expand Down
28 changes: 28 additions & 0 deletions Client/Internal/ApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using InfluxDB.Client.Core.Internal;
using RestSharp;
using RestSharp.Authenticators;

namespace InfluxDB.Client.Api.Client
{
Expand Down Expand Up @@ -126,6 +128,16 @@ private void InitToken()
if (authResponse.Cookies != null)
{
_initializedSessionTokens = true;
// The cookies doesn't follow redirects => we have to manually set `Cookie` header by Authenticator.
if (_options.AllowHttpRedirects && authResponse.Cookies.Count > 0)
{
var headerParameter = authResponse
.Headers?
.FirstOrDefault(it =>
string.Equals("Set-Cookie", it.Name, StringComparison.OrdinalIgnoreCase));

RestClient.Authenticator = new CookieRedirectAuthenticator(headerParameter);
}
}
}
}
Expand All @@ -145,6 +157,22 @@ protected internal void Signout()

var request = new RestRequest("/api/v2/signout", Method.Post);
RestClient.ExecuteAsync(request).ConfigureAwait(false).GetAwaiter().GetResult();
RestClient.Authenticator = null;
}
}

/// <summary>
/// Set Cookies to HTTP Request.
/// </summary>
internal class CookieRedirectAuthenticator : AuthenticatorBase
{
internal CookieRedirectAuthenticator(Parameter setCookie) : base(setCookie.Value?.ToString() ?? "")
{
}

protected override ValueTask<Parameter> GetAuthenticationParameter(string cookie)
{
return new ValueTask<Parameter>(new HeaderParameter("Cookie", cookie));
}
}
}