Skip to content
Draft
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
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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;
}
21 changes: 21 additions & 0 deletions src/main/java/com/descope/sdk/auth/AuthenticationService.java
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -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<String> authHeader = new AtomicReference<>();

AccessKeyAuthenticationInfo info;
try (MockedStatic<ApiProxyBuilder> mockedApiProxyBuilder = mockStatic(ApiProxyBuilder.class)) {
mockedApiProxyBuilder.when(() -> ApiProxyBuilder.buildProxy(any(), any())).thenAnswer(inv -> {
authHeader.compareAndSet(null, ((Supplier<String>) inv.getArgument(0)).get());
return apiProxy;
});
try (MockedStatic<JwtUtils> mockedJwtUtils = mockStatic(JwtUtils.class)) {
mockedJwtUtils.when(() -> JwtUtils.getToken(anyString(), any())).thenReturn(MOCK_TOKEN);
info = authenticationService.exchangeAccessKeyAuthenticationInfo("someAccessKey", loginOptions);
}
}

ArgumentCaptor<URI> uriCaptor = ArgumentCaptor.forClass(URI.class);
ArgumentCaptor<Map<String, Object>> 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<ApiProxyBuilder> mockedApiProxyBuilder = mockStatic(ApiProxyBuilder.class)) {
mockedApiProxyBuilder.when(() -> ApiProxyBuilder.buildProxy(any(), any())).thenReturn(apiProxy);
try (MockedStatic<JwtUtils> 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<ApiProxyBuilder> 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);
Expand Down