From 3c71d4b6e5eff9d28e6673fcfcacd062074970e2 Mon Sep 17 00:00:00 2001 From: "martin.scholz" Date: Tue, 23 Jul 2024 12:28:25 +0200 Subject: [PATCH 1/2] CI-3316 Java SDK using username and password still --- .../main/java/com/emnify/sdk/ApiClient.java | 31 ---------- .../com/emnify/sdk/auth/HttpBasicAuth.java | 62 ------------------- 2 files changed, 93 deletions(-) delete mode 100644 api/src/main/java/com/emnify/sdk/auth/HttpBasicAuth.java diff --git a/api/src/main/java/com/emnify/sdk/ApiClient.java b/api/src/main/java/com/emnify/sdk/ApiClient.java index b78691d..75ba49f 100644 --- a/api/src/main/java/com/emnify/sdk/ApiClient.java +++ b/api/src/main/java/com/emnify/sdk/ApiClient.java @@ -35,7 +35,6 @@ import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; -import java.net.URI; import java.net.URLConnection; import java.net.URLEncoder; import java.nio.file.Files; @@ -46,7 +45,6 @@ import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; import java.text.DateFormat; import java.time.LocalDate; import java.time.OffsetDateTime; @@ -58,7 +56,6 @@ import java.util.regex.Pattern; import com.emnify.sdk.auth.Authentication; -import com.emnify.sdk.auth.HttpBasicAuth; import com.emnify.sdk.auth.HttpBearerAuth; import com.emnify.sdk.auth.ApiKeyAuth; @@ -323,35 +320,7 @@ public void setBearerToken(String bearerToken) { throw new RuntimeException("No Bearer authentication configured!"); } - /** - * Helper method to set username for the first HTTP basic authentication. - * - * @param username Username - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - /** - * Helper method to set password for the first HTTP basic authentication. - * - * @param password Password - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } /** * Helper method to set API key value for the first API key authentication. diff --git a/api/src/main/java/com/emnify/sdk/auth/HttpBasicAuth.java b/api/src/main/java/com/emnify/sdk/auth/HttpBasicAuth.java deleted file mode 100644 index 5ac1a0d..0000000 --- a/api/src/main/java/com/emnify/sdk/auth/HttpBasicAuth.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * #%L - * EMnify Java SDK - * %% - * Copyright (C) 2021 EMnify - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ - - -package com.emnify.sdk.auth; - -import com.emnify.sdk.Pair; - -import okhttp3.Credentials; - -import java.util.Map; -import java.util.List; - -import java.io.UnsupportedEncodingException; - -public class HttpBasicAuth implements Authentication { - private String username; - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public void applyToParams(List queryParams, Map headerParams, Map cookieParams) { - if (username == null && password == null) { - return; - } - headerParams.put("Authorization", Credentials.basic( - username == null ? "" : username, - password == null ? "" : password)); - } -} From dc9f7cf70553b32d4c6147305c7c5a3f81450046 Mon Sep 17 00:00:00 2001 From: "martin.scholz" Date: Tue, 23 Jul 2024 14:55:46 +0200 Subject: [PATCH 2/2] CI-3316 deleting username password --- README.md | 1 - api/docs/Authentication.md | 2 - .../com/emnify/sdk/model/Authentication.java | 55 +--- .../emnify/sdk/model/AuthenticationTest.java | 15 -- .../java/com/emnify/sdk/client/EMnify.java | 20 -- .../sdk/client/auth/BasicAuthentication.java | 103 -------- .../sdk/client/config/Configuration.java | 7 - .../emnify/sdk/client/EMnifyClientTest.java | 40 --- .../java/com/emnify/sdk/client/TestSuite.java | 2 - .../ApplicationTokenAuthenticationTest.java | 2 - .../client/auth/BasicAuthenticationTest.java | 245 ------------------ .../sdk/client/config/ConfigurationTest.java | 15 -- examples/quota-management/README.md | 4 - 13 files changed, 1 insertion(+), 510 deletions(-) delete mode 100644 emnify/src/main/java/com/emnify/sdk/client/auth/BasicAuthentication.java delete mode 100644 emnify/src/test/java/com/emnify/sdk/client/auth/BasicAuthenticationTest.java diff --git a/README.md b/README.md index 73b2fed..fb4b91c 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,6 @@ You can use environment variables for storing configuration settings like an app |--------------------|--------------------------------------------------------------------------| | `EMNIFY_BASE_PATH` | Base URL to form a request. Default value: `https://cdn.emnify.net` | | `EMNIFY_APPLICATION_TOKEN` | Variable for authenticating via an [application token](https://cdn.emnify.net/api/doc/application-token.html). | -| `EMNIFY_USERNAME` and `EMNIFY_PASSWORD` | Variables for authenticating via [username and password](https://cdn.emnify.net/api/doc/basic-auth.html). | ## Documentation diff --git a/api/docs/Authentication.md b/api/docs/Authentication.md index 93c808a..a87bc95 100644 --- a/api/docs/Authentication.md +++ b/api/docs/Authentication.md @@ -8,8 +8,6 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **applicationToken** | **String** | | [optional] -**username** | **String** | | [optional] -**password** | **String** | | [optional] **refreshToken** | **String** | | [optional] diff --git a/api/src/main/java/com/emnify/sdk/model/Authentication.java b/api/src/main/java/com/emnify/sdk/model/Authentication.java index 2a5d1e8..94c21a1 100644 --- a/api/src/main/java/com/emnify/sdk/model/Authentication.java +++ b/api/src/main/java/com/emnify/sdk/model/Authentication.java @@ -41,13 +41,6 @@ public class Authentication { @SerializedName(SERIALIZED_NAME_APPLICATION_TOKEN) private String applicationToken; - public static final String SERIALIZED_NAME_USERNAME = "username"; - @SerializedName(SERIALIZED_NAME_USERNAME) - private String username; - - public static final String SERIALIZED_NAME_PASSWORD = "password"; - @SerializedName(SERIALIZED_NAME_PASSWORD) - private String password; public static final String SERIALIZED_NAME_REFRESH_TOKEN = "refresh_token"; @SerializedName(SERIALIZED_NAME_REFRESH_TOKEN) @@ -77,50 +70,8 @@ public void setApplicationToken(String applicationToken) { } - public Authentication username(String username) { - - this.username = username; - return this; - } - - /** - * Get username - * @return username - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - - public String getUsername() { - return username; - } - - - public void setUsername(String username) { - this.username = username; - } - public Authentication password(String password) { - - this.password = password; - return this; - } - - /** - * Get password - * @return password - **/ - @javax.annotation.Nullable - @ApiModelProperty(value = "") - - public String getPassword() { - return password; - } - - - public void setPassword(String password) { - this.password = password; - } public Authentication refreshToken(String refreshToken) { @@ -156,14 +107,12 @@ public boolean equals(Object o) { } Authentication authentication = (Authentication) o; return Objects.equals(this.applicationToken, authentication.applicationToken) && - Objects.equals(this.username, authentication.username) && - Objects.equals(this.password, authentication.password) && Objects.equals(this.refreshToken, authentication.refreshToken); } @Override public int hashCode() { - return Objects.hash(applicationToken, username, password, refreshToken); + return Objects.hash(applicationToken, refreshToken); } @Override @@ -171,8 +120,6 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Authentication {\n"); sb.append(" applicationToken: ").append(toIndentedString(applicationToken)).append("\n"); - sb.append(" username: ").append(toIndentedString(username)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append(" refreshToken: ").append(toIndentedString(refreshToken)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/api/src/test/java/com/emnify/sdk/model/AuthenticationTest.java b/api/src/test/java/com/emnify/sdk/model/AuthenticationTest.java index 6894add..918eca0 100644 --- a/api/src/test/java/com/emnify/sdk/model/AuthenticationTest.java +++ b/api/src/test/java/com/emnify/sdk/model/AuthenticationTest.java @@ -56,21 +56,6 @@ public void applicationTokenTest() { // TODO: test applicationToken } - /** - * Test the property 'username' - */ - @Test - public void usernameTest() { - // TODO: test username - } - - /** - * Test the property 'password' - */ - @Test - public void passwordTest() { - // TODO: test password - } /** * Test the property 'refreshToken' diff --git a/emnify/src/main/java/com/emnify/sdk/client/EMnify.java b/emnify/src/main/java/com/emnify/sdk/client/EMnify.java index 4c3b0ec..7489dc0 100644 --- a/emnify/src/main/java/com/emnify/sdk/client/EMnify.java +++ b/emnify/src/main/java/com/emnify/sdk/client/EMnify.java @@ -35,8 +35,6 @@ public class EMnify { private static final String APPLICATION_TOKEN_ENV = "EMNIFY_APPLICATION_TOKEN"; - private static final String USERNAME_ENV = "EMNIFY_USERNAME"; - private static final String PASSWORD_ENV = "EMNIFY_PASSWORD"; private final Authentication authentication; private final AuthenticationRetrier authenticationRetrier; @@ -52,7 +50,6 @@ private EMnify(Authentication authentication, ApiClient apiClient) { * Performs api client authorization according to configured system environment variables: * * @return instance of authorized EMnify Client * @throws SdkException if authentication failed @@ -61,27 +58,10 @@ public static EMnify authenticate() throws SdkException { Authentication authentication; authentication = createAuthentication(SystemUtils.getEnvironmentVariable(APPLICATION_TOKEN_ENV, "")); - if (authentication == null) { - String username = SystemUtils.getEnvironmentVariable(USERNAME_ENV, ""); - String password = SystemUtils.getEnvironmentVariable(PASSWORD_ENV, ""); - authentication = Configuration.createAuthentication(username, password); - } return authenticate(authentication); } - /** - * Performs api client authorization with user/password combination - * - * @param username username - * @param password password - * - * @return instance of authorized EMnify Client - * @throws SdkException if authentication failed - */ - public static EMnify authenticate(String username, String password) throws SdkException { - return authenticate(Configuration.createAuthentication(username, password)); - } /** * Performs api client authorization with application token diff --git a/emnify/src/main/java/com/emnify/sdk/client/auth/BasicAuthentication.java b/emnify/src/main/java/com/emnify/sdk/client/auth/BasicAuthentication.java deleted file mode 100644 index fb7525f..0000000 --- a/emnify/src/main/java/com/emnify/sdk/client/auth/BasicAuthentication.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * #%L - * EMnify Java SDK - * %% - * Copyright (C) 2021 EMnify - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ - -package com.emnify.sdk.client.auth; - -import java.security.MessageDigest; - -import com.emnify.sdk.ApiClient; -import com.emnify.sdk.ApiException; -import com.emnify.sdk.api.AuthenticationApi; -import com.emnify.sdk.client.exception.SdkApiException; -import com.emnify.sdk.client.exception.SdkException; -import com.emnify.sdk.model.AuthenticationResponse; -import lombok.ToString; - -@ToString -public class BasicAuthentication extends AbstractAuthentication { - - private final String username; - private final String password; - - public BasicAuthentication(String username, String password) { - this.username = username; - this.password = password; - } - - @Override - public void authenticate(ApiClient apiClient) throws SdkException { - try { - if (isExpired()) { - AuthenticationApi authClient = new AuthenticationApi(apiClient); - - com.emnify.sdk.model.Authentication userAuth = new com.emnify.sdk.model.Authentication(); - if (isRefreshTokenValid()) { - userAuth.setRefreshToken(tokens.getRefreshToken().getToken()); - tokens.getRefreshToken().setValid(false); - } else { - userAuth.setUsername(username); - userAuth.setPassword(stringToHex(hash(password))); - } - - AuthenticationResponse response = authClient.authenticate(userAuth); - apiClient.setBearerToken(response.getAuthToken()); - - tokens = new AuthenticationTokens(response.getAuthToken(), response.getRefreshToken()); - } - } catch (ApiException e) { - throw SdkApiException.create("Unable to authenticate user: " + username, e); - } - } - - /** - * Checks if authentication refresh token is not expired and was not used - * - * @return false if token for refreshing is expired or invalid otherwise true - */ - public boolean isRefreshTokenValid() { - if (tokens != null) { - AuthenticationTokens.JWTData refreshToken = tokens.getRefreshToken(); - if (refreshToken != null) { - return refreshToken.isValid() && !tokens.getRefreshToken().isExpired(); - } - } - - return false; - } - - private static byte[] hash(String password) throws SdkException { - try { - MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); - messageDigest.update(password.getBytes()); - - return messageDigest.digest(); - } catch (Exception e) { - throw new SdkException("Unable to compute hash while authorizing: " + e.getMessage()); - } - } - - private static String stringToHex(byte[] a) { - StringBuilder sb = new StringBuilder(a.length * 2); - for (byte b : a) { - sb.append(String.format("%02x", b)); - } - return sb.toString(); - } -} diff --git a/emnify/src/main/java/com/emnify/sdk/client/config/Configuration.java b/emnify/src/main/java/com/emnify/sdk/client/config/Configuration.java index 7192622..5b0ba56 100644 --- a/emnify/src/main/java/com/emnify/sdk/client/config/Configuration.java +++ b/emnify/src/main/java/com/emnify/sdk/client/config/Configuration.java @@ -23,7 +23,6 @@ import com.emnify.sdk.ApiClient; import com.emnify.sdk.client.auth.ApplicationTokenAuthentication; import com.emnify.sdk.client.auth.Authentication; -import com.emnify.sdk.client.auth.BasicAuthentication; import com.emnify.sdk.client.retrier.AuthenticationRetrier; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; @@ -40,13 +39,7 @@ public static ApiClient getApiClient() { return apiClient; } - public static Authentication createAuthentication(String username, String password) { - if (StringUtils.isNotBlank(username) || StringUtils.isNotBlank(password)) { - return new BasicAuthentication(username, password); - } - return null; - } public static Authentication createAuthentication(String appToken) { if (StringUtils.isNotBlank(appToken)) { diff --git a/emnify/src/test/java/com/emnify/sdk/client/EMnifyClientTest.java b/emnify/src/test/java/com/emnify/sdk/client/EMnifyClientTest.java index 0ef376f..556fadf 100644 --- a/emnify/src/test/java/com/emnify/sdk/client/EMnifyClientTest.java +++ b/emnify/src/test/java/com/emnify/sdk/client/EMnifyClientTest.java @@ -24,7 +24,6 @@ import com.emnify.sdk.ApiClient; import com.emnify.sdk.client.auth.ApplicationTokenAuthentication; -import com.emnify.sdk.client.auth.BasicAuthentication; import com.emnify.sdk.client.config.Configuration; import com.emnify.sdk.client.exception.SdkException; import com.emnify.sdk.client.auth.AuthenticationTokens; @@ -50,8 +49,6 @@ @PrepareForTest({Configuration.class, EMnify.class}) public class EMnifyClientTest { - private static final String USERNAME = TestUtils.generateString(); - private static final String PASSWORD = TestUtils.generateString(); private static final String APPLICATION_TOKEN = TestUtils.getJWTToken(null); private static final Date TOKEN_EXPIRATION_DATE = DateUtils.addMinutes(new Date(), 5); @@ -144,42 +141,5 @@ public void test_authenticate_application_token_exception() throws Exception { verify(mock).authenticate(apiClientMock); } - @Test - public void test_authenticate_basic() throws Exception { - BasicAuthentication mock = mock(BasicAuthentication.class); - - whenNew(BasicAuthentication.class) - .withArguments(USERNAME, PASSWORD) - .thenReturn(mock); - - AuthenticationTokens tokens = new AuthenticationTokens(AUTH_TOKEN, REFRESH_TOKEN); - - // execute - EMnify client = EMnify.authenticate(USERNAME, PASSWORD); - - // verify - verifyNew(BasicAuthentication.class).withArguments(USERNAME, PASSWORD); - verify(mock).authenticate(apiClientMock); - - // assert - assertNotNull(client); - } - - @Test - public void test_authenticate_basic_exception() throws Exception { - BasicAuthentication mock = mock(BasicAuthentication.class); - - whenNew(BasicAuthentication.class) - .withArguments(USERNAME, PASSWORD) - .thenReturn(mock); - - doThrow(new SdkException("Exception occurs")).when(mock).authenticate(apiClientMock); - - // execute - TestUtils.expectException(() -> EMnify.authenticate(USERNAME, PASSWORD), SdkException.class); - // verify - verifyNew(BasicAuthentication.class).withArguments(USERNAME, PASSWORD); - verify(mock).authenticate(apiClientMock); - } } diff --git a/emnify/src/test/java/com/emnify/sdk/client/TestSuite.java b/emnify/src/test/java/com/emnify/sdk/client/TestSuite.java index 089bdfc..e262e79 100644 --- a/emnify/src/test/java/com/emnify/sdk/client/TestSuite.java +++ b/emnify/src/test/java/com/emnify/sdk/client/TestSuite.java @@ -21,7 +21,6 @@ package com.emnify.sdk.client; import com.emnify.sdk.client.auth.ApplicationTokenAuthenticationTest; -import com.emnify.sdk.client.auth.BasicAuthenticationTest; import com.emnify.sdk.client.config.ConfigurationTest; import com.emnify.sdk.client.model.AuthenticationTokensTest; import com.emnify.sdk.client.model.QuotaActionOnExhaustionTest; @@ -38,7 +37,6 @@ // auth package AuthenticationTokensTest.class, ApplicationTokenAuthenticationTest.class, - BasicAuthenticationTest.class, // retrier AuthenticationRetrierTest.class, diff --git a/emnify/src/test/java/com/emnify/sdk/client/auth/ApplicationTokenAuthenticationTest.java b/emnify/src/test/java/com/emnify/sdk/client/auth/ApplicationTokenAuthenticationTest.java index c703e39..a36adfc 100644 --- a/emnify/src/test/java/com/emnify/sdk/client/auth/ApplicationTokenAuthenticationTest.java +++ b/emnify/src/test/java/com/emnify/sdk/client/auth/ApplicationTokenAuthenticationTest.java @@ -87,8 +87,6 @@ public void test_Authenticate_Default() throws Exception { // verify verify(requestMock).setApplicationToken(APPLICATION_TOKEN); - verify(requestMock, never()).setUsername(any()); - verify(requestMock, never()).setPassword(any()); verify(authApiMock).authenticate(requestMock); verify(apiClientMock).setBearerToken(AUTH_TOKEN); diff --git a/emnify/src/test/java/com/emnify/sdk/client/auth/BasicAuthenticationTest.java b/emnify/src/test/java/com/emnify/sdk/client/auth/BasicAuthenticationTest.java deleted file mode 100644 index f4b70ec..0000000 --- a/emnify/src/test/java/com/emnify/sdk/client/auth/BasicAuthenticationTest.java +++ /dev/null @@ -1,245 +0,0 @@ -/*- - * #%L - * EMnify Java SDK - * %% - * Copyright (C) 2021 EMnify - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ - -package com.emnify.sdk.client.auth; - -import java.util.Date; - -import com.emnify.sdk.ApiClient; -import com.emnify.sdk.ApiException; -import com.emnify.sdk.api.AuthenticationApi; -import com.emnify.sdk.client.config.Configuration; -import com.emnify.sdk.client.exception.SdkApiException; -import com.emnify.sdk.client.exception.SdkException; -import com.emnify.sdk.client.util.TestUtils; -import com.emnify.sdk.model.Authentication; -import com.emnify.sdk.model.AuthenticationResponse; -import org.apache.commons.lang3.time.DateUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import static com.emnify.sdk.client.util.TestUtils.expectException; -import static com.emnify.sdk.client.util.TestUtils.setupApiClientMock; -import static com.emnify.sdk.client.util.TestUtils.setupAuthenticationApiMock; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({Configuration.class, BasicAuthentication.class}) -public class BasicAuthenticationTest { - - private static final Date TOKEN_EXPIRATION_DATE = DateUtils.addMinutes(new Date(), 5); - private static final Date REFRESH_TOKEN_EXPIRATION_DATE = DateUtils.addMinutes(new Date(), 10); - - private static final String AUTH_TOKEN = TestUtils.getJWTToken(TOKEN_EXPIRATION_DATE); - private static final String EXPIRED_AUTH_TOKEN = TestUtils.getJWTToken(DateUtils.addMinutes(new Date(), -10)); - private static final String REFRESH_TOKEN = TestUtils.getJWTToken(REFRESH_TOKEN_EXPIRATION_DATE); - - private static final String USERNAME = TestUtils.generateString(); - private static final String PASSWORD = "secretPassword"; - private static final String HASHED_PASSWORD = "5b41eb73810d06f17bc7585fae9a87ecf677fe5c"; - - @Mock - private ApiClient apiClientMock; - - @Mock - private AuthenticationApi authApiMock; - - @Before - public void setUp() throws Exception { - setupApiClientMock(apiClientMock); - setupAuthenticationApiMock(authApiMock, apiClientMock); - } - - @Test - public void test_Authenticate_Default() throws Exception { - Authentication requestMock = mock(Authentication.class); - whenNew(Authentication.class) - .withNoArguments() - .thenReturn(requestMock); - - AuthenticationResponse response = new AuthenticationResponse(); - response.setAuthToken(AUTH_TOKEN); - response.setRefreshToken(REFRESH_TOKEN); - - when(authApiMock.authenticate(requestMock)).thenReturn(response); - - // execute - BasicAuthentication authentication = new BasicAuthentication(USERNAME, PASSWORD); - authentication.authenticate(apiClientMock); - - // assert - assertFalse(authentication.isExpired()); - assertTrue(authentication.isRefreshTokenValid()); - - // verify - verify(requestMock).setUsername(USERNAME); - verify(requestMock).setPassword(HASHED_PASSWORD); - verify(requestMock, never()).setApplicationToken(any()); - - verify(authApiMock).authenticate(requestMock); - verify(apiClientMock).setBearerToken(AUTH_TOKEN); - - } - - @Test - public void test_Authenticate_InvalidRefreshToken() throws Exception { - Authentication requestMock = mock(Authentication.class); - whenNew(Authentication.class) - .withNoArguments() - .thenReturn(requestMock); - - AuthenticationResponse expiredTokensResponse = new AuthenticationResponse(); - expiredTokensResponse.setAuthToken(EXPIRED_AUTH_TOKEN); - expiredTokensResponse.setRefreshToken(EXPIRED_AUTH_TOKEN); - - AuthenticationResponse response = new AuthenticationResponse(); - response.setAuthToken(AUTH_TOKEN); - response.setRefreshToken(REFRESH_TOKEN); - - when(authApiMock.authenticate(requestMock)).thenReturn(expiredTokensResponse).thenReturn(response); - - // execute - BasicAuthentication authentication = new BasicAuthentication(USERNAME, PASSWORD); - authentication.authenticate(apiClientMock); - - assertTrue(authentication.isExpired()); - assertFalse(authentication.isRefreshTokenValid()); - - // execute one more time when auth token is set as expired - authentication.authenticate(apiClientMock); - - // assert - assertFalse(authentication.isExpired()); - assertTrue(authentication.isRefreshTokenValid()); - - // verify - verify(requestMock, times(2)).setUsername(USERNAME); - verify(requestMock, times(2)).setPassword(HASHED_PASSWORD); - verify(requestMock, never()).setRefreshToken(EXPIRED_AUTH_TOKEN); - verify(requestMock, never()).setApplicationToken(any()); - - verify(authApiMock, times(2)).authenticate(requestMock); - verify(apiClientMock).setBearerToken(EXPIRED_AUTH_TOKEN); - verify(apiClientMock).setBearerToken(AUTH_TOKEN); - } - - @Test - public void test_Authenticate_ExpiredToken() throws Exception { - Authentication requestMock = mock(Authentication.class); - whenNew(Authentication.class) - .withNoArguments() - .thenReturn(requestMock); - - AuthenticationResponse expiredTokenResponse = new AuthenticationResponse(); - expiredTokenResponse.setAuthToken(EXPIRED_AUTH_TOKEN); - expiredTokenResponse.setRefreshToken(REFRESH_TOKEN); - - AuthenticationResponse response = new AuthenticationResponse(); - response.setAuthToken(AUTH_TOKEN); - response.setRefreshToken(REFRESH_TOKEN); - - when(authApiMock.authenticate(requestMock)).thenReturn(expiredTokenResponse).thenReturn(response); - - // execute - BasicAuthentication authentication = new BasicAuthentication(USERNAME, PASSWORD); - authentication.authenticate(apiClientMock); - - // assert - assertTrue(authentication.isExpired()); - assertTrue(authentication.isRefreshTokenValid()); - - // execute one more time when auth token is set as expired - authentication.authenticate(apiClientMock); - - // assert - assertFalse(authentication.isExpired()); - assertTrue(authentication.isRefreshTokenValid()); - - // verify - verify(requestMock).setUsername(USERNAME); - verify(requestMock).setPassword(HASHED_PASSWORD); - verify(requestMock).setRefreshToken(REFRESH_TOKEN); - verify(requestMock, never()).setApplicationToken(any()); - - verify(authApiMock, times(2)).authenticate(requestMock); - verify(apiClientMock).setBearerToken(EXPIRED_AUTH_TOKEN); - verify(apiClientMock).setBearerToken(AUTH_TOKEN); - - } - - @Test - public void test_Authenticate_EmptyPassword() throws Exception { - Authentication requestMock = mock(Authentication.class); - whenNew(Authentication.class) - .withNoArguments() - .thenReturn(requestMock); - - AuthenticationResponse response = new AuthenticationResponse(); - response.setAuthToken(AUTH_TOKEN); - - when(authApiMock.authenticate(requestMock)).thenReturn(response); - - // execute - expectException( - () -> new BasicAuthentication(USERNAME, null).authenticate(apiClientMock), - SdkException.class, "Unable to compute hash while authorizing: null"); - - // verify - verify(requestMock).setUsername(USERNAME); - verify(requestMock, never()).setPassword(""); - verify(requestMock, never()).setApplicationToken(any()); - - verify(authApiMock, never()).authenticate(requestMock); - verify(apiClientMock, never()).setBearerToken(AUTH_TOKEN); - - } - - @Test - public void test_Authenticate_Exception() throws Exception { - Authentication requestMock = mock(Authentication.class); - whenNew(Authentication.class).withNoArguments().thenReturn(requestMock); - - when(authApiMock.authenticate(requestMock)).thenThrow(new ApiException()); - - // execute - expectException( - () -> new BasicAuthentication(USERNAME, PASSWORD).authenticate(apiClientMock), - SdkApiException.class, "Unable to authenticate user: " + USERNAME + " Cause: null null"); - - // verify - verify(requestMock).setUsername(USERNAME); - verify(requestMock).setPassword(HASHED_PASSWORD); - verify(requestMock, never()).setApplicationToken(any()); - - verify(authApiMock).authenticate(requestMock); - verify(apiClientMock, never()).setBearerToken(AUTH_TOKEN); - } -} diff --git a/emnify/src/test/java/com/emnify/sdk/client/config/ConfigurationTest.java b/emnify/src/test/java/com/emnify/sdk/client/config/ConfigurationTest.java index aeec553..c644f99 100644 --- a/emnify/src/test/java/com/emnify/sdk/client/config/ConfigurationTest.java +++ b/emnify/src/test/java/com/emnify/sdk/client/config/ConfigurationTest.java @@ -29,21 +29,6 @@ public class ConfigurationTest { - @Test - public void test_createAuthentication_UsernamePassword_Default() { - Authentication authentication = Configuration.createAuthentication("username", "password"); - - assertNotNull(authentication); - assertTrue(authentication.isExpired()); - assertFalse(authentication.isRefreshTokenValid()); - } - - @Test - public void test_createAuthentication_UsernamePassword_EmptyFields() { - Authentication authentication = Configuration.createAuthentication("", ""); - - assertNull(authentication); - } @Test public void test_createAuthentication_BytApplicationToken_Default() { diff --git a/examples/quota-management/README.md b/examples/quota-management/README.md index 4dd87de..fbae2d6 100644 --- a/examples/quota-management/README.md +++ b/examples/quota-management/README.md @@ -32,10 +32,6 @@ There are two ways to do this: To [authenticate via application token](https://cdn.emnify.net/api/doc/application-token.html), you need to add `EMNIFY_APPLICATION_TOKEN` as an [environment variable](../../README.md#environment-variables). -#### User authentication - - -If you want to [authenticate via user authentication](https://cdn.emnify.net/api/doc/basic-auth.html), you need to add the `EMNIFY_USERNAME` and `EMNIFY_PASSWORD` [environment variables](../../README.md#environment-variables). ### Execute the example