Skip to content

Commit 798ff29

Browse files
authored
fix: session authentication for InfluxDB 2.1 (#279)
* fix: session authentication for InfluxDB 2.1 * docs: update CHANGELOG.md
1 parent 7e4b969 commit 798ff29

4 files changed

Lines changed: 49 additions & 25 deletions

File tree

CHANGELOG.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@
77

88
### Features
99
1. [#272](https://github.com/influxdata/influxdb-client-java/pull/272): Add `PingService` to check status of OSS and Cloud instance
10-
2. [#278](https://github.com/influxdata/influxdb-client-java/pull/278): Add query method with all params for BucketsApi, OrganizationApi and TasksApi
10+
1. [#278](https://github.com/influxdata/influxdb-client-java/pull/278): Add query method with all params for BucketsApi, OrganizationApi and TasksApi
11+
12+
### Bug Fixes
13+
1. [#279](https://github.com/influxdata/influxdb-client-java/pull/279): Session authentication for InfluxDB `2.1`
1114

1215
### CI
1316
1. [#275](https://github.com/influxdata/influxdb-client-java/pull/275): Deploy `influxdb-client-test` package into Maven repository

client/src/main/java/com/influxdb/client/internal/AuthenticateInterceptor.java

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@
3333
import com.influxdb.client.InfluxDBClientOptions;
3434

3535
import okhttp3.Call;
36-
import okhttp3.Cookie;
3736
import okhttp3.Credentials;
3837
import okhttp3.HttpUrl;
3938
import okhttp3.Interceptor;
@@ -56,8 +55,8 @@ class AuthenticateInterceptor implements Interceptor {
5655

5756
private OkHttpClient okHttpClient;
5857

59-
private char[] sessionToken;
60-
private AtomicBoolean signout = new AtomicBoolean(false);
58+
private char[] sessionCookies;
59+
private final AtomicBoolean signout = new AtomicBoolean(false);
6160

6261
AuthenticateInterceptor(@Nonnull final InfluxDBClientOptions influxDBClientOptions) {
6362

@@ -67,6 +66,7 @@ class AuthenticateInterceptor implements Interceptor {
6766
}
6867

6968
@Override
69+
@Nonnull
7070
public Response intercept(@Nonnull final Chain chain) throws IOException {
7171

7272
Request request = chain.request();
@@ -87,9 +87,9 @@ public Response intercept(@Nonnull final Chain chain) throws IOException {
8787

8888
initToken(this.okHttpClient);
8989

90-
if (sessionToken != null) {
90+
if (sessionCookies != null) {
9191
request = request.newBuilder()
92-
.header("Cookie", "session=" + string(sessionToken))
92+
.header("Cookie", string(sessionCookies))
9393
.build();
9494
}
9595
}
@@ -111,27 +111,22 @@ void initToken(@Nonnull final OkHttpClient okHttpClient) {
111111
return;
112112
}
113113

114-
//TODO or expired
115-
if (sessionToken == null) {
114+
if (sessionCookies == null) {
116115

117116
String credentials = Credentials
118117
.basic(influxDBClientOptions.getUsername(), string(influxDBClientOptions.getPassword()));
119118

120119
Request authRequest = new Request.Builder()
121120
.url(buildPath("api/v2/signin"))
122121
.addHeader("Authorization", credentials)
123-
.post(RequestBody.create(null, ""))
122+
.post(RequestBody.create("application/json", null))
124123
.build();
125124

126125
try (Response authResponse = this.okHttpClient.newCall(authRequest).execute()) {
126+
String cookieHeader = authResponse.headers().get("Set-Cookie");
127127

128-
Cookie sessionCookie = Cookie.parseAll(authRequest.url(), authResponse.headers()).stream()
129-
.filter(cookie -> "session".equals(cookie.name()))
130-
.findFirst()
131-
.orElse(null);
132-
133-
if (sessionCookie != null) {
134-
sessionToken = sessionCookie.value().toCharArray();
128+
if (cookieHeader != null) {
129+
sessionCookies = cookieHeader.toCharArray();
135130
}
136131
} catch (IOException e) {
137132
LOG.log(Level.WARNING, "Cannot retrieve the Session token!", e);
@@ -152,15 +147,18 @@ void signout() throws IOException {
152147
return;
153148
}
154149

155-
this.signout.set(true);
156-
this.sessionToken = null;
157-
158-
Request authRequest = new Request.Builder()
150+
Request.Builder authRequest = new Request.Builder()
159151
.url(buildPath("api/v2/signout"))
160-
.post(RequestBody.create(null, ""))
161-
.build();
152+
.post(RequestBody.create("application/json", null));
153+
154+
if (sessionCookies != null) {
155+
authRequest.addHeader("Cookie", string(sessionCookies));
156+
}
157+
158+
signout.set(true);
159+
sessionCookies = null;
162160

163-
Response response = this.okHttpClient.newCall(authRequest).execute();
161+
Response response = okHttpClient.newCall(authRequest.build()).execute();
164162
response.close();
165163
}
166164

client/src/test/java/com/influxdb/client/ITInfluxDBClient.java

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,20 @@
2424
import java.io.IOException;
2525
import java.time.OffsetDateTime;
2626
import java.time.ZoneOffset;
27+
import java.util.List;
2728

29+
import com.influxdb.LogLevel;
2830
import com.influxdb.client.domain.HealthCheck;
2931
import com.influxdb.client.domain.OnboardingRequest;
3032
import com.influxdb.client.domain.OnboardingResponse;
3133
import com.influxdb.client.domain.Ready;
3234
import com.influxdb.client.domain.Routes;
3335
import com.influxdb.client.domain.User;
36+
import com.influxdb.client.domain.WritePrecision;
3437
import com.influxdb.client.service.RoutesService;
3538
import com.influxdb.exceptions.InfluxException;
3639
import com.influxdb.exceptions.UnprocessableEntityException;
40+
import com.influxdb.query.FluxTable;
3741

3842
import org.assertj.core.api.Assertions;
3943
import org.junit.jupiter.api.Test;
@@ -61,7 +65,7 @@ void health() {
6165
void healthNotRunningInstance() {
6266

6367
InfluxDBClient clientNotRunning = InfluxDBClientFactory.create("http://localhost:8099");
64-
HealthCheck check = clientNotRunning.health();
68+
HealthCheck check = clientNotRunning.health();
6569

6670
Assertions.assertThat(check).isNotNull();
6771
Assertions.assertThat(check.getName()).isEqualTo("influxdb");
@@ -220,4 +224,23 @@ void routesService() throws IOException {
220224
Assertions.assertThat(routes.getUsers()).isEqualTo("/api/v2/users");
221225
Assertions.assertThat(routes.getWrite()).isEqualTo("/api/v2/write");
222226
}
227+
228+
@Test
229+
void useUsernamePassword() {
230+
try (InfluxDBClient client = InfluxDBClientFactory.create(influxDB_URL, "my-user", "my-password".toCharArray())) {
231+
String measurement = "mem_" + System.currentTimeMillis();
232+
client
233+
.getWriteApiBlocking()
234+
.writeRecord("my-bucket", "my-org", WritePrecision.NS, measurement + ",tag=a value=5.0");
235+
236+
String flux = "from(bucket: \"my-bucket\")\n" +
237+
" |> range(start: 0)" +
238+
" |> filter(fn: (r) => r[\"_measurement\"] == \""+measurement+"\")";
239+
240+
List<FluxTable> tables = client.getQueryApi().query(flux, "my-org");
241+
Assertions.assertThat(tables).hasSize(1);
242+
Assertions.assertThat(tables.get(0).getRecords()).hasSize(1);
243+
Assertions.assertThat(tables.get(0).getRecords().get(0).getValue()).isEqualTo(5.0);
244+
}
245+
}
223246
}

client/src/test/java/com/influxdb/client/internal/AuthenticateInterceptorTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ void authorizationSession() throws IOException, InterruptedException {
117117
RecordedRequest requestToTasks = mockServer.takeRequest();
118118
Assertions.assertThat(requestToTasks.getPath()).endsWith("/api/v2/tasks");
119119
Assertions.assertThat(requestToTasks.getHeader("Cookie"))
120-
.isEqualTo("session=yCgXaEBF8mYSmJUweRcW0g_5jElMs7mv6_-G1bNcau4Z0ZLQYtj0BkHZYRnBVA6uXHtyuhflcOzyNDNRxnaC0A==");
120+
.isEqualTo("session=yCgXaEBF8mYSmJUweRcW0g_5jElMs7mv6_-G1bNcau4Z0ZLQYtj0BkHZYRnBVA6uXHtyuhflcOzyNDNRxnaC0A==; path=/api/v2");
121121
}
122122

123123
@Test

0 commit comments

Comments
 (0)