Skip to content
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

fix: session authentication for InfluxDB 2.1 #279

Merged
merged 2 commits into from
Nov 15, 2021
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
Expand Up @@ -7,7 +7,10 @@

### Features
1. [#272](https://github.com/influxdata/influxdb-client-java/pull/272): Add `PingService` to check status of OSS and Cloud instance
2. [#278](https://github.com/influxdata/influxdb-client-java/pull/278): Add query method with all params for BucketsApi, OrganizationApi and TasksApi
1. [#278](https://github.com/influxdata/influxdb-client-java/pull/278): Add query method with all params for BucketsApi, OrganizationApi and TasksApi

### Bug Fixes
1. [#279](https://github.com/influxdata/influxdb-client-java/pull/279): Session authentication for InfluxDB `2.1`

### CI
1. [#275](https://github.com/influxdata/influxdb-client-java/pull/275): Deploy `influxdb-client-test` package into Maven repository
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import com.influxdb.client.InfluxDBClientOptions;

import okhttp3.Call;
import okhttp3.Cookie;
import okhttp3.Credentials;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
Expand All @@ -56,8 +55,8 @@ class AuthenticateInterceptor implements Interceptor {

private OkHttpClient okHttpClient;

private char[] sessionToken;
private AtomicBoolean signout = new AtomicBoolean(false);
private char[] sessionCookies;
private final AtomicBoolean signout = new AtomicBoolean(false);

AuthenticateInterceptor(@Nonnull final InfluxDBClientOptions influxDBClientOptions) {

Expand All @@ -67,6 +66,7 @@ class AuthenticateInterceptor implements Interceptor {
}

@Override
@Nonnull
public Response intercept(@Nonnull final Chain chain) throws IOException {

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

initToken(this.okHttpClient);

if (sessionToken != null) {
if (sessionCookies != null) {
request = request.newBuilder()
.header("Cookie", "session=" + string(sessionToken))
.header("Cookie", string(sessionCookies))
.build();
}
}
Expand All @@ -111,27 +111,22 @@ void initToken(@Nonnull final OkHttpClient okHttpClient) {
return;
}

//TODO or expired
if (sessionToken == null) {
if (sessionCookies == null) {

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

Request authRequest = new Request.Builder()
.url(buildPath("api/v2/signin"))
.addHeader("Authorization", credentials)
.post(RequestBody.create(null, ""))
.post(RequestBody.create("application/json", null))
.build();

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

Cookie sessionCookie = Cookie.parseAll(authRequest.url(), authResponse.headers()).stream()
.filter(cookie -> "session".equals(cookie.name()))
.findFirst()
.orElse(null);

if (sessionCookie != null) {
sessionToken = sessionCookie.value().toCharArray();
if (cookieHeader != null) {
sessionCookies = cookieHeader.toCharArray();
}
} catch (IOException e) {
LOG.log(Level.WARNING, "Cannot retrieve the Session token!", e);
Expand All @@ -152,15 +147,18 @@ void signout() throws IOException {
return;
}

this.signout.set(true);
this.sessionToken = null;

Request authRequest = new Request.Builder()
Request.Builder authRequest = new Request.Builder()
.url(buildPath("api/v2/signout"))
.post(RequestBody.create(null, ""))
.build();
.post(RequestBody.create("application/json", null));

if (sessionCookies != null) {
authRequest.addHeader("Cookie", string(sessionCookies));
}

signout.set(true);
sessionCookies = null;

Response response = this.okHttpClient.newCall(authRequest).execute();
Response response = okHttpClient.newCall(authRequest.build()).execute();
response.close();
}

Expand Down
25 changes: 24 additions & 1 deletion client/src/test/java/com/influxdb/client/ITInfluxDBClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,20 @@
import java.io.IOException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.List;

import com.influxdb.LogLevel;
import com.influxdb.client.domain.HealthCheck;
import com.influxdb.client.domain.OnboardingRequest;
import com.influxdb.client.domain.OnboardingResponse;
import com.influxdb.client.domain.Ready;
import com.influxdb.client.domain.Routes;
import com.influxdb.client.domain.User;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.service.RoutesService;
import com.influxdb.exceptions.InfluxException;
import com.influxdb.exceptions.UnprocessableEntityException;
import com.influxdb.query.FluxTable;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -61,7 +65,7 @@ void health() {
void healthNotRunningInstance() {

InfluxDBClient clientNotRunning = InfluxDBClientFactory.create("http://localhost:8099");
HealthCheck check = clientNotRunning.health();
HealthCheck check = clientNotRunning.health();

Assertions.assertThat(check).isNotNull();
Assertions.assertThat(check.getName()).isEqualTo("influxdb");
Expand Down Expand Up @@ -220,4 +224,23 @@ void routesService() throws IOException {
Assertions.assertThat(routes.getUsers()).isEqualTo("/api/v2/users");
Assertions.assertThat(routes.getWrite()).isEqualTo("/api/v2/write");
}

@Test
void useUsernamePassword() {
try (InfluxDBClient client = InfluxDBClientFactory.create(influxDB_URL, "my-user", "my-password".toCharArray())) {
String measurement = "mem_" + System.currentTimeMillis();
client
.getWriteApiBlocking()
.writeRecord("my-bucket", "my-org", WritePrecision.NS, measurement + ",tag=a value=5.0");

String flux = "from(bucket: \"my-bucket\")\n" +
" |> range(start: 0)" +
" |> filter(fn: (r) => r[\"_measurement\"] == \""+measurement+"\")";

List<FluxTable> tables = client.getQueryApi().query(flux, "my-org");
Assertions.assertThat(tables).hasSize(1);
Assertions.assertThat(tables.get(0).getRecords()).hasSize(1);
Assertions.assertThat(tables.get(0).getRecords().get(0).getValue()).isEqualTo(5.0);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ void authorizationSession() throws IOException, InterruptedException {
RecordedRequest requestToTasks = mockServer.takeRequest();
Assertions.assertThat(requestToTasks.getPath()).endsWith("/api/v2/tasks");
Assertions.assertThat(requestToTasks.getHeader("Cookie"))
.isEqualTo("session=yCgXaEBF8mYSmJUweRcW0g_5jElMs7mv6_-G1bNcau4Z0ZLQYtj0BkHZYRnBVA6uXHtyuhflcOzyNDNRxnaC0A==");
.isEqualTo("session=yCgXaEBF8mYSmJUweRcW0g_5jElMs7mv6_-G1bNcau4Z0ZLQYtj0BkHZYRnBVA6uXHtyuhflcOzyNDNRxnaC0A==; path=/api/v2");
}

@Test
Expand Down