|
| 1 | +package io.a2a.client.transport.spi.interceptors.auth; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.concurrent.CompletableFuture; |
| 6 | + |
| 7 | +import io.a2a.client.transport.spi.interceptors.ClientCallContext; |
| 8 | + |
| 9 | +/** |
| 10 | + * A simple in-memory store for session-keyed credentials. |
| 11 | + * This class uses the 'sessionId' from the {@code ClientCallContext} state to |
| 12 | + * store and retrieve credentials |
| 13 | + */ |
| 14 | +public class InMemoryContextCredentialService implements CredentialService { |
| 15 | + |
| 16 | + private static final String SESSION_ID = "sessionId"; |
| 17 | + |
| 18 | + // maps a sessionId to a map of security scheme names to credentials |
| 19 | + private final Map<String, Map<String, String>> credentialStore; |
| 20 | + |
| 21 | + public InMemoryContextCredentialService() { |
| 22 | + credentialStore = new HashMap<>(); |
| 23 | + } |
| 24 | + |
| 25 | + @Override |
| 26 | + public CompletableFuture<String> getCredentials(String securitySchemeName, |
| 27 | + ClientCallContext clientCallContext) { |
| 28 | + if (clientCallContext == null || !clientCallContext.getState().containsKey(SESSION_ID)) { |
| 29 | + // no credential to retrieve |
| 30 | + return CompletableFuture.completedFuture(null); |
| 31 | + } |
| 32 | + |
| 33 | + String sessionId = (String) clientCallContext.getState().get(SESSION_ID); |
| 34 | + Map<String, String> sessionCredentials = credentialStore.getOrDefault(sessionId, new HashMap<>()); |
| 35 | + String credential = sessionCredentials.get(securitySchemeName); |
| 36 | + return CompletableFuture.completedFuture(credential); |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Method to populate the in-memory credential service. |
| 41 | + * |
| 42 | + * @param sessionId the session ID |
| 43 | + * @param securitySchemeName the name of the security scheme |
| 44 | + * @param credential the credential string |
| 45 | + */ |
| 46 | + public void setCredential(String sessionId, String securitySchemeName, String credential) { |
| 47 | + Map<String, String> sessionIdCredentials = credentialStore.getOrDefault(sessionId, new HashMap<>()); |
| 48 | + sessionIdCredentials.put(securitySchemeName, credential); |
| 49 | + } |
| 50 | +} |
0 commit comments