From e8a2b29110f46f6c9e3eed0fcf766e4a03f37310 Mon Sep 17 00:00:00 2001 From: Yosi Haran Date: Fri, 20 Nov 2026 11:51:36 +0200 Subject: [PATCH] feat(auth): return the access key ID on access key exchange --- README.md | 19 ++++ .../auth/AccessKeyAuthenticationInfo.java | 14 +++ .../response/ExchangeAccessKeyResponse.java | 14 +++ .../sdk/auth/AuthenticationService.java | 21 +++++ .../auth/impl/AuthenticationServiceImpl.java | 21 ++++- .../impl/AuthenticationServiceImplTest.java | 92 +++++++++++++++++++ 6 files changed, 177 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/descope/model/auth/AccessKeyAuthenticationInfo.java create mode 100644 src/main/java/com/descope/model/jwt/response/ExchangeAccessKeyResponse.java diff --git a/README.md b/README.md index b12d8837..5f7347cb 100644 --- a/README.md +++ b/README.md @@ -524,6 +524,25 @@ The implementation can defer according to your implementation. See our [examples If Roles & Permissions are used, validate them immediately after validating the session. See the [next section](#roles--permission-validation) for more information. +#### Exchanging an Access Key + +An access key can be exchanged for a session token: + +```java +AuthenticationService as = descopeClient.getAuthenticationServices().getAuthService(); +try { + // Optionally add custom claims to the session token + AccessKeyLoginOptions loginOptions = new AccessKeyLoginOptions(mapOf("k1", "v1")); + Token t = as.exchangeAccessKey(accessKey, loginOptions); + // Or get the ID of the exchanged access key along with the session token + AccessKeyAuthenticationInfo info = as.exchangeAccessKeyAuthenticationInfo(accessKey, loginOptions); + String keyId = info.getKeyId(); + Token sessionToken = info.getToken(); +} catch (DescopeException de) { + // Handle the unauthorized error +} +``` + #### Session Validation Using Middleware Alternatively, you can validate the session using Spring Framework middleware. See example using [java-spring](https://github.com/descope/java-spring). diff --git a/src/main/java/com/descope/model/auth/AccessKeyAuthenticationInfo.java b/src/main/java/com/descope/model/auth/AccessKeyAuthenticationInfo.java new file mode 100644 index 00000000..315017b1 --- /dev/null +++ b/src/main/java/com/descope/model/auth/AccessKeyAuthenticationInfo.java @@ -0,0 +1,14 @@ +package com.descope.model.auth; + +import com.descope.model.jwt.Token; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class AccessKeyAuthenticationInfo { + private Token token; // session token + private String keyId; // ID of the exchanged access key +} diff --git a/src/main/java/com/descope/model/jwt/response/ExchangeAccessKeyResponse.java b/src/main/java/com/descope/model/jwt/response/ExchangeAccessKeyResponse.java new file mode 100644 index 00000000..aac34432 --- /dev/null +++ b/src/main/java/com/descope/model/jwt/response/ExchangeAccessKeyResponse.java @@ -0,0 +1,14 @@ +package com.descope.model.jwt.response; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Data +@NoArgsConstructor +@EqualsAndHashCode(callSuper = true) +@ToString(callSuper = true) +public class ExchangeAccessKeyResponse extends JWTResponse { + private String keyId; +} diff --git a/src/main/java/com/descope/sdk/auth/AuthenticationService.java b/src/main/java/com/descope/sdk/auth/AuthenticationService.java index c8f3b971..e02e9285 100644 --- a/src/main/java/com/descope/sdk/auth/AuthenticationService.java +++ b/src/main/java/com/descope/sdk/auth/AuthenticationService.java @@ -1,6 +1,7 @@ package com.descope.sdk.auth; import com.descope.exception.DescopeException; +import com.descope.model.auth.AccessKeyAuthenticationInfo; import com.descope.model.auth.AccessKeyLoginOptions; import com.descope.model.auth.AuthenticationInfo; import com.descope.model.jwt.Token; @@ -101,6 +102,26 @@ AuthenticationInfo validateAndRefreshSessionWithTokensAuthenticationInfo(String */ Token exchangeAccessKey(String accessKey, AccessKeyLoginOptions loginOptions) throws DescopeException; + /** + * Use to exchange an access key for a session token, also returning the ID of the access key. + * + * @param accessKey - Access Key + * @return {@link AccessKeyAuthenticationInfo the session token and the access key ID} + * @throws DescopeException if there is an error + */ + AccessKeyAuthenticationInfo exchangeAccessKeyAuthenticationInfo(String accessKey) throws DescopeException; + + /** + * Use to exchange an access key for a session token with login options, also returning the ID of the access key. + * + * @param accessKey - Access Key + * @param loginOptions - {@link AccessKeyLoginOptions loginOptions} + * @return {@link AccessKeyAuthenticationInfo the session token and the access key ID} + * @throws DescopeException if there is an error + */ + AccessKeyAuthenticationInfo exchangeAccessKeyAuthenticationInfo(String accessKey, + AccessKeyLoginOptions loginOptions) throws DescopeException; + /** * Use to ensure that a validated session token has been granted the specified permissions. This * is a shortcut for validatePermissions(token, "", permissions) diff --git a/src/main/java/com/descope/sdk/auth/impl/AuthenticationServiceImpl.java b/src/main/java/com/descope/sdk/auth/impl/AuthenticationServiceImpl.java index 6774c9f7..b23f4e18 100644 --- a/src/main/java/com/descope/sdk/auth/impl/AuthenticationServiceImpl.java +++ b/src/main/java/com/descope/sdk/auth/impl/AuthenticationServiceImpl.java @@ -12,11 +12,13 @@ import com.descope.exception.DescopeException; import com.descope.exception.ServerCommonException; +import com.descope.model.auth.AccessKeyAuthenticationInfo; import com.descope.model.auth.AccessKeyLoginOptions; import com.descope.model.auth.AuthenticationInfo; import com.descope.model.auth.ExchangeTokenRequest; import com.descope.model.client.Client; import com.descope.model.jwt.Token; +import com.descope.model.jwt.response.ExchangeAccessKeyResponse; import com.descope.model.jwt.response.JWTResponse; import com.descope.model.user.response.UserHistoryResponse; import com.descope.model.user.response.UserResponse; @@ -113,16 +115,27 @@ public Token exchangeAccessKey(String accessKey) throws DescopeException { @Override public Token exchangeAccessKey(String accessKey, AccessKeyLoginOptions loginOptions) throws DescopeException { + return exchangeAccessKeyAuthenticationInfo(accessKey, loginOptions).getToken(); + } + + @Override + public AccessKeyAuthenticationInfo exchangeAccessKeyAuthenticationInfo(String accessKey) throws DescopeException { + return exchangeAccessKeyAuthenticationInfo(accessKey, null); + } + + @Override + public AccessKeyAuthenticationInfo exchangeAccessKeyAuthenticationInfo(String accessKey, + AccessKeyLoginOptions loginOptions) throws DescopeException { if (StringUtils.isBlank(accessKey)) { throw ServerCommonException.invalidArgument("accessKey"); } ApiProxy apiProxy = getApiProxy(accessKey); URI exchangeAccessKeyLinkURL = composeExchangeAccessKeyLinkURL(); - JWTResponse jwtResponse = apiProxy.post(exchangeAccessKeyLinkURL, - mapOf("loginOptions", loginOptions), JWTResponse.class); - AuthenticationInfo authenticationInfo = getAuthenticationInfo(jwtResponse); - return authenticationInfo.getToken(); + ExchangeAccessKeyResponse response = apiProxy.post(exchangeAccessKeyLinkURL, + mapOf("loginOptions", loginOptions), ExchangeAccessKeyResponse.class); + AuthenticationInfo authenticationInfo = getAuthenticationInfo(response); + return new AccessKeyAuthenticationInfo(authenticationInfo.getToken(), response.getKeyId()); } @Override diff --git a/src/test/java/com/descope/sdk/auth/impl/AuthenticationServiceImplTest.java b/src/test/java/com/descope/sdk/auth/impl/AuthenticationServiceImplTest.java index a930ff74..6e181f0c 100644 --- a/src/test/java/com/descope/sdk/auth/impl/AuthenticationServiceImplTest.java +++ b/src/test/java/com/descope/sdk/auth/impl/AuthenticationServiceImplTest.java @@ -1,25 +1,42 @@ package com.descope.sdk.auth.impl; +import static com.descope.sdk.TestUtils.MOCK_SIGNING_KEY; import static com.descope.sdk.TestUtils.MOCK_TOKEN; +import static com.descope.sdk.TestUtils.PROJECT_ID; import static com.descope.utils.CollectionUtils.mapOf; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import com.descope.enums.DeliveryMethod; import com.descope.exception.RateLimitExceededException; +import com.descope.exception.ServerCommonException; +import com.descope.model.auth.AccessKeyAuthenticationInfo; import com.descope.model.auth.AccessKeyLoginOptions; import com.descope.model.auth.AuthenticationInfo; import com.descope.model.auth.AuthenticationServices; import com.descope.model.client.Client; import com.descope.model.jwt.Token; +import com.descope.model.jwt.response.ExchangeAccessKeyResponse; +import com.descope.model.jwt.response.SigningKeysResponse; import com.descope.model.mgmt.AccessKeyResponse; import com.descope.model.mgmt.ManagementServices; import com.descope.model.user.request.UserRequest; import com.descope.model.user.response.OTPTestUserResponse; import com.descope.model.user.response.UserResponse; +import com.descope.proxy.ApiProxy; +import com.descope.proxy.impl.ApiProxyBuilder; import com.descope.sdk.TestUtils; import com.descope.sdk.auth.AuthenticationService; import com.descope.sdk.auth.OTPService; @@ -28,10 +45,16 @@ import com.descope.sdk.mgmt.TenantService; import com.descope.sdk.mgmt.UserService; import com.descope.sdk.mgmt.impl.ManagementServiceBuilder; +import com.descope.utils.JwtUtils; +import java.net.URI; import java.util.Arrays; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; import org.junitpioneer.jupiter.RetryingTest; public class AuthenticationServiceImplTest { @@ -84,6 +107,75 @@ void testGetMatchedPermissionsAndRoles() { authenticationService.getMatchedPermissions(MOCK_TOKEN, Arrays.asList("p1", "p2", "p3"))); } + @Test + @SuppressWarnings("unchecked") + void testExchangeAccessKeyAuthenticationInfo() { + ExchangeAccessKeyResponse response = new ExchangeAccessKeyResponse(); + response.setSessionJwt("someSessionJwt"); + response.setKeyId("someKeyId"); + ApiProxy apiProxy = mock(ApiProxy.class); + doReturn(response).when(apiProxy).post(any(), any(), eq(ExchangeAccessKeyResponse.class)); + doReturn(new SigningKeysResponse(Arrays.asList(MOCK_SIGNING_KEY))) + .when(apiProxy).get(any(), eq(SigningKeysResponse.class)); + AccessKeyLoginOptions loginOptions = new AccessKeyLoginOptions(mapOf("k1", "v1")); + AtomicReference authHeader = new AtomicReference<>(); + + AccessKeyAuthenticationInfo info; + try (MockedStatic mockedApiProxyBuilder = mockStatic(ApiProxyBuilder.class)) { + mockedApiProxyBuilder.when(() -> ApiProxyBuilder.buildProxy(any(), any())).thenAnswer(inv -> { + authHeader.compareAndSet(null, ((Supplier) inv.getArgument(0)).get()); + return apiProxy; + }); + try (MockedStatic mockedJwtUtils = mockStatic(JwtUtils.class)) { + mockedJwtUtils.when(() -> JwtUtils.getToken(anyString(), any())).thenReturn(MOCK_TOKEN); + info = authenticationService.exchangeAccessKeyAuthenticationInfo("someAccessKey", loginOptions); + } + } + + ArgumentCaptor uriCaptor = ArgumentCaptor.forClass(URI.class); + ArgumentCaptor> bodyCaptor = ArgumentCaptor.forClass(Map.class); + verify(apiProxy).post(uriCaptor.capture(), bodyCaptor.capture(), eq(ExchangeAccessKeyResponse.class)); + assertEquals("/v1/auth/accesskey/exchange", uriCaptor.getValue().getPath()); + assertEquals(mapOf("loginOptions", loginOptions), bodyCaptor.getValue()); + assertEquals("Bearer " + PROJECT_ID + ":someAccessKey", authHeader.get()); + assertEquals(MOCK_TOKEN, info.getToken()); + assertEquals("someKeyId", info.getKeyId()); + } + + @Test + void testExchangeAccessKeyStillReturnsToken() { + ExchangeAccessKeyResponse response = new ExchangeAccessKeyResponse(); + response.setSessionJwt("someSessionJwt"); + response.setKeyId("someKeyId"); + ApiProxy apiProxy = mock(ApiProxy.class); + doReturn(response).when(apiProxy).post(any(), any(), eq(ExchangeAccessKeyResponse.class)); + doReturn(new SigningKeysResponse(Arrays.asList(MOCK_SIGNING_KEY))) + .when(apiProxy).get(any(), eq(SigningKeysResponse.class)); + + Token token; + try (MockedStatic mockedApiProxyBuilder = mockStatic(ApiProxyBuilder.class)) { + mockedApiProxyBuilder.when(() -> ApiProxyBuilder.buildProxy(any(), any())).thenReturn(apiProxy); + try (MockedStatic mockedJwtUtils = mockStatic(JwtUtils.class)) { + mockedJwtUtils.when(() -> JwtUtils.getToken(anyString(), any())).thenReturn(MOCK_TOKEN); + token = authenticationService.exchangeAccessKey("someAccessKey"); + } + } + assertEquals(MOCK_TOKEN, token); + } + + @Test + void testExchangeAccessKeyAuthenticationInfoEmptyAccessKey() { + ApiProxy apiProxy = mock(ApiProxy.class); + try (MockedStatic mockedApiProxyBuilder = mockStatic(ApiProxyBuilder.class)) { + mockedApiProxyBuilder.when(() -> ApiProxyBuilder.buildProxy(any(), any())).thenReturn(apiProxy); + ServerCommonException thrown = assertThrows(ServerCommonException.class, + () -> authenticationService.exchangeAccessKeyAuthenticationInfo("")); + assertNotNull(thrown); + assertThat(thrown.getMessage()).contains("accessKey"); + } + verify(apiProxy, never()).post(any(), any(), any()); + } + @RetryingTest(value = 3, suspendForMs = 30000, onExceptions = RateLimitExceededException.class) void testFunctionalPermissions() { String roleName = TestUtils.getRandomName("r-").substring(0, 20);