From afc9c6f6d80532ba50ec5f6b879f73f552f82833 Mon Sep 17 00:00:00 2001 From: Ioannis Kakavas Date: Fri, 2 Aug 2019 13:30:45 +0300 Subject: [PATCH] Adds test for authentication with an invalid token Ensure that we return 401 when an invalid token is presented as the Bearer token Relates: #38866 --- .../security/authc/TokenAuthIntegTests.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenAuthIntegTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenAuthIntegTests.java index 59bd9f04fedf4..893919035920c 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenAuthIntegTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenAuthIntegTests.java @@ -268,6 +268,23 @@ public void testRefreshingToken() throws IOException { .admin().cluster().prepareHealth().get()); } + public void testAuthenticateWithWrongToken() throws IOException { + final RestHighLevelClient restClient = new TestRestHighLevelClient(); + CreateTokenResponse response = restClient.security().createToken(CreateTokenRequest.passwordGrant( + SecuritySettingsSource.TEST_USER_NAME, SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()), SECURITY_REQUEST_OPTIONS); + assertNotNull(response.getRefreshToken()); + // First check that the correct access token works by getting cluster health with token + assertNoTimeout(client() + .filterWithHeader(Collections.singletonMap("Authorization", "Bearer " + response.getAccessToken())) + .admin().cluster().prepareHealth().get()); + // Now attempt to authenticate with an invalid access token string + RequestOptions wrongAuthOptions = + RequestOptions.DEFAULT.toBuilder().addHeader("Authorization", "Bearer " + randomAlphaOfLengthBetween(0, 128)).build(); + ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, + () -> restClient.security().authenticate(wrongAuthOptions)); + assertEquals(RestStatus.UNAUTHORIZED, e.status()); + } + public void testRefreshingInvalidatedToken() throws IOException { final RestHighLevelClient restClient = new TestRestHighLevelClient(); CreateTokenResponse createTokenResponse = restClient.security().createToken(CreateTokenRequest.passwordGrant(