001package ca.cdr.test.app.clients;
002/*-
003 * #%L
004 * Smile CDR - CDR
005 * %%
006 * Copyright (C) 2016 - 2026 Smile CDR, Inc.
007 * %%
008 * All rights reserved.
009 * #L%
010 */
011
012import com.google.gson.Gson;
013import com.google.gson.JsonElement;
014import com.google.gson.JsonObject;
015import jakarta.annotation.Nonnull;
016import jakarta.annotation.Nullable;
017import org.apache.commons.codec.binary.Base64;
018import org.slf4j.Logger;
019import org.slf4j.LoggerFactory;
020import org.springframework.http.HttpHeaders;
021import org.springframework.http.MediaType;
022import org.springframework.http.ResponseEntity;
023import org.springframework.util.LinkedMultiValueMap;
024import org.springframework.util.MultiValueMap;
025import org.springframework.web.client.RestClient;
026import org.springframework.web.client.RestClientException;
027import org.springframework.web.util.UriComponentsBuilder;
028import tools.jackson.databind.JsonNode;
029
030import java.io.IOException;
031import java.net.URI;
032import java.net.URLEncoder;
033import java.nio.charset.StandardCharsets;
034import java.util.Arrays;
035import java.util.List;
036import java.util.Objects;
037
038import static org.apache.commons.lang3.StringUtils.isNotBlank;
039
040// Created by Claude Sonnet 4
041
042/**
043 * A client for performing SMART on FHIR OAuth 2.0 authorization flows.
044 *
045 * <p>This client provides methods to interact with SMART on FHIR OAuth 2.0 endpoints
046 * and supports the following OAuth 2.0 flows:</p>
047 * <ul>
048 *   <li><strong>Authorization Code Flow</strong> - For web applications requiring user consent</li>
049 *   <li><strong>Client Credentials Flow</strong> - For backend services, authenticating with a
050 *       client secret or a signed JWT assertion</li>
051 *   <li><strong>Refresh Token Flow</strong></li>
052 *   <li><strong>Token Introspection</strong> and <strong>OpenID Connect discovery</strong></li>
053 * </ul>
054 *
055 * <p>The client handles HTTP communication with the SMART authorization server,
056 * form-based authentication, CSRF token management, and token exchange operations.</p>
057 *
058 * <h3>Thread Safety:</h3>
059 * <p>This client is not thread-safe. Each thread should use its own instance
060 * or external synchronization should be applied.</p>
061 *
062 * @author Claude Sonnet 4
063 * @see <a href="http://hl7.org/fhir/smart-app-launch/">SMART App Launch Framework</a>
064 * @see <a href="https://tools.ietf.org/html/rfc6749">OAuth 2.0 Authorization Framework</a>
065 */
066public class OutboundSmartClient {
067        private static final Logger ourLog = LoggerFactory.getLogger(OutboundSmartClient.class);
068
069        private static final String CLIENT_ASSERTION_TYPE_JWT_BEARER =
070                        "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
071        private static final String GRANT_TYPE_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
072
073        private final RestClient myRestClient;
074        private final String mySmartRootUrl;
075
076        /**
077         * Creates a new OutboundSmartClient instance.
078         *
079         * @param theRestClient the REST client to use for HTTP communication with the SMART server.
080         *                      This client should be configured with appropriate timeouts, SSL settings,
081         *                      and cookie management as needed for the target SMART server.
082         * @param theSmartRootUrl the root URL of the SMART authorization server (e.g., "https://auth.example.com"),
083         *                        including any context path. This should not include trailing slashes or
084         *                        specific endpoints. When it has a context path, {@code theRestClient}'s base
085         *                        URL must end in a slash so that request paths resolve beneath it.
086         *                        Its message converters are replaced by ones that read JSON with Jackson 3.
087         * @throws NullPointerException if either parameter is null
088         */
089        public OutboundSmartClient(@Nonnull RestClient theRestClient, @Nonnull String theSmartRootUrl) {
090                myRestClient = Objects.requireNonNull(theRestClient, "theRestClient must not be null")
091                                .mutate()
092                                .configureMessageConverters(ClientMessageConverters::configure)
093                                .build();
094                mySmartRootUrl = Objects.requireNonNull(theSmartRootUrl, "theSmartRootUrl must not be null");
095        }
096        /**
097         * Exchanges an authorization code for an access token with flexible client authentication.
098         *
099         * <p>This method provides full control over how the client secret is transmitted to the
100         * authorization server. It supports both HTTP Basic authentication (in the Authorization header)
101         * and form parameter authentication (in the request body).</p>
102         *
103         * <p>The method constructs a form-encoded POST request to the token endpoint with the
104         * authorization code and other required parameters. The response is parsed to extract
105         * the access token.</p>
106         *
107         * @param theClientId the OAuth 2.0 client identifier. Must not be null.
108         * @param theClientSecret the client secret. If null, no client authentication is performed.
109         * @param theCode the authorization code to exchange. Must not be null.
110         * @param secret_as_param if true, the client secret is sent as a form parameter (client_secret);
111         *                        if false, the client secret is sent via HTTP Basic authentication
112         *                        in the Authorization header. This parameter is ignored if theClientSecret is null.
113         * @return the access token as a string
114         * @throws IOException if the token exchange request fails or if the response cannot be parsed
115         * @see <a href="https://tools.ietf.org/html/rfc6749#section-4.1.3">RFC 6749 Section 4.1.3</a>
116         */
117        public String exchangeCodeWithSecret(
118                        String theClientId, String theClientSecret, String theCode, String theRedirectUri, boolean secret_as_param)
119                        throws IOException {
120
121                // Validate required parameters
122                if (theClientId == null || theClientId.trim().isEmpty()) {
123                        throw new IllegalArgumentException("theClientId must not be null or empty");
124                }
125                if (theCode == null || theCode.trim().isEmpty()) {
126                        throw new IllegalArgumentException("theCode must not be null or empty");
127                }
128
129                // Build form data string directly
130                String formData = "code=" + theCode + "&grant_type=authorization_code"
131                                + "&redirect_uri="
132                                + URLEncoder.encode(theRedirectUri) + "&client_id="
133                                + theClientId;
134
135                // Build the request
136                RestClient.RequestBodySpec requestSpec =
137                                myRestClient.post().uri("/oauth/token").contentType(MediaType.APPLICATION_FORM_URLENCODED);
138
139                // Add authorization header if needed
140                if (isNotBlank(theClientSecret)) {
141                        if (secret_as_param) {
142                                formData += "&client_secret=" + theClientSecret;
143                        } else {
144                                String auth = "Basic "
145                                                + Base64.encodeBase64String(
146                                                                (theClientId + ":" + theClientSecret).getBytes(StandardCharsets.UTF_8));
147                                requestSpec.header("Authorization", auth);
148                        }
149                }
150
151                // Execute the request and process response
152                String respString = requestSpec.body(formData).retrieve().body(String.class);
153
154                ourLog.debug("Resp: {}", respString);
155
156                JsonObject respObj = new Gson().fromJson(respString, JsonObject.class);
157
158                // Safely extract access_token
159                JsonElement accessTokenElement = respObj.get("access_token");
160                if (accessTokenElement == null || accessTokenElement.isJsonNull()) {
161                        throw new IOException("access_token not found in response");
162                }
163                return accessTokenElement.getAsString();
164        }
165
166        /**
167         * Refreshes an access token using a refresh token.
168         *
169         * <p>When an access token expires, a refresh token (if available) can be used to obtain
170         * a new access token without requiring the user to re-authorize the application.
171         * This method performs the token refresh operation.</p>
172         *
173         * <p>The authorization server may issue a new refresh token along with the new access token,
174         * and the old refresh token should be considered invalid.</p>
175         *
176         * @param theClientId the OAuth 2.0 client identifier. Must match the original client that
177         *                    obtained the refresh token. Must not be null or empty.
178         * @param theClientSecret the OAuth 2.0 client secret, sent with HTTP Basic authentication. May be
179         *                        null for a public client, which sends {@code client_id} as a form
180         *                        parameter instead.
181         * @param theRefreshToken the refresh token obtained from a previous token request.
182         *                        Must not be null or empty.
183         * @return JSON document as a string containing the new access token and potentially a new
184         *         refresh token. Typical response includes: access_token, token_type, expires_in,
185         *         refresh_token (optional), scope. {@link AccessTokenResponse#fromJson(JsonNode)} reads it.
186         * @throws IllegalArgumentException if required parameters are null or empty
187         * @see <a href="https://tools.ietf.org/html/rfc6749#section-6">RFC 6749 Section 6</a>
188         */
189        @Nonnull
190        public String refreshToken(
191                        @Nonnull String theClientId, @Nullable String theClientSecret, @Nonnull String theRefreshToken) {
192                requireNotBlank(theClientId, "theClientId");
193                requireNotBlank(theRefreshToken, "theRefreshToken");
194
195                MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
196                form.add("grant_type", "refresh_token");
197                form.add("refresh_token", theRefreshToken);
198                if (theClientSecret == null) {
199                        form.add("client_id", theClientId);
200                }
201                return Objects.requireNonNull(
202                                postForm("oauth/token", form, theClientSecret == null ? null : theClientId, theClientSecret)
203                                                .body(String.class));
204        }
205
206        /**
207         * Obtains an access token with the client credentials grant, authenticating with a client
208         * secret sent via HTTP Basic authentication.
209         *
210         * @param theClientId the OAuth 2.0 client identifier
211         * @param theClientSecret the client secret
212         * @param theScopes the scopes to request; none leaves the {@code scope} parameter out
213         * @return the token endpoint's response
214         * @see <a href="https://tools.ietf.org/html/rfc6749#section-4.4">RFC 6749 Section 4.4</a>
215         */
216        @Nonnull
217        public AccessTokenResponse clientCredentials(
218                        @Nonnull String theClientId, @Nonnull String theClientSecret, @Nullable String... theScopes) {
219                requireNotBlank(theClientId, "theClientId");
220                requireNotBlank(theClientSecret, "theClientSecret");
221
222                MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
223                form.add("grant_type", "client_credentials");
224                addScope(form, theScopes);
225                return tokenResponse(postForm("oauth/token", form, theClientId, theClientSecret));
226        }
227
228        /**
229         * Obtains an access token with the client credentials grant, authenticating with a signed JWT
230         * client assertion, as SMART Backend Services clients do. This client only transports the
231         * assertion: building and signing it is the caller's job.
232         *
233         * @param theClientId the OAuth 2.0 client identifier, sent as {@code client_id}
234         * @param theSignedJwtAssertion the signed JWT, sent as {@code client_assertion}
235         * @param theScopes the scopes to request; none leaves the {@code scope} parameter out
236         * @return the token endpoint's response
237         * @see <a href="https://datatracker.ietf.org/doc/html/rfc7523#section-2.2">RFC 7523 Section 2.2</a>
238         */
239        @Nonnull
240        public AccessTokenResponse clientCredentialsWithAssertion(
241                        @Nonnull String theClientId, @Nonnull String theSignedJwtAssertion, @Nullable String... theScopes) {
242                requireNotBlank(theClientId, "theClientId");
243                requireNotBlank(theSignedJwtAssertion, "theSignedJwtAssertion");
244
245                MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
246                form.add("grant_type", "client_credentials");
247                form.add("client_id", theClientId);
248                form.add("client_assertion_type", CLIENT_ASSERTION_TYPE_JWT_BEARER);
249                form.add("client_assertion", theSignedJwtAssertion);
250                addScope(form, theScopes);
251                return tokenResponse(postForm("oauth/token", form, null, null));
252        }
253
254        @Nonnull
255        public AccessTokenResponse jwtBearerWithAssertion(
256                        @Nonnull String theAuthorizationGrant,
257                        @Nonnull String theSignedJwtAssertion,
258                        @Nullable String... theScopes) {
259                requireNotBlank(theAuthorizationGrant, "theAuthorizationGrant");
260                requireNotBlank(theSignedJwtAssertion, "theSignedJwtAssertion");
261
262                MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
263                form.add("grant_type", GRANT_TYPE_JWT_BEARER);
264                form.add("assertion", theAuthorizationGrant);
265                form.add("client_assertion_type", CLIENT_ASSERTION_TYPE_JWT_BEARER);
266                form.add("client_assertion", theSignedJwtAssertion);
267                addScope(form, theScopes);
268                return tokenResponse(postForm("oauth/token", form, null, null));
269        }
270
271        /**
272         * Asks the server whether a token is active, authenticating as a client with HTTP Basic
273         * authentication.
274         *
275         * @param theToken the access or refresh token to introspect
276         * @param theClientId the client to authenticate as
277         * @param theClientSecret that client's secret
278         * @return the introspection response, whose {@code active} member says whether the token is live
279         * @see <a href="https://datatracker.ietf.org/doc/html/rfc7662">RFC 7662</a>
280         */
281        @Nonnull
282        public JsonNode introspect(@Nonnull String theToken, @Nonnull String theClientId, @Nonnull String theClientSecret) {
283                requireNotBlank(theToken, "theToken");
284                requireNotBlank(theClientId, "theClientId");
285                requireNotBlank(theClientSecret, "theClientSecret");
286
287                MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
288                form.add("token", theToken);
289                return Objects.requireNonNull(postForm("oauth/token/introspect", form, theClientId, theClientSecret)
290                                .body(JsonNode.class));
291        }
292
293        /**
294         * Fetches the server's OpenID Connect discovery document.
295         *
296         * @return the contents of {@code .well-known/openid-configuration}
297         */
298        @Nonnull
299        public JsonNode openIdConfiguration() {
300                return Objects.requireNonNull(myRestClient
301                                .get()
302                                .uri(".well-known/openid-configuration")
303                                .retrieve()
304                                .body(JsonNode.class));
305        }
306
307        private RestClient.ResponseSpec postForm(
308                        String theUri,
309                        MultiValueMap<String, String> theForm,
310                        @Nullable String theBasicUser,
311                        @Nullable String theBasicPassword) {
312                return myRestClient
313                                .post()
314                                .uri(theUri)
315                                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
316                                .accept(MediaType.APPLICATION_JSON)
317                                .headers(headers -> {
318                                        if (theBasicUser != null && theBasicPassword != null) {
319                                                headers.set(HttpHeaders.AUTHORIZATION, basicAuth(theBasicUser, theBasicPassword));
320                                        }
321                                })
322                                .body(theForm)
323                                .retrieve();
324        }
325
326        private static AccessTokenResponse tokenResponse(RestClient.ResponseSpec theResponse) {
327                return AccessTokenResponse.fromJson(Objects.requireNonNull(theResponse.body(JsonNode.class)));
328        }
329
330        private void addScope(MultiValueMap<String, String> theForm, String[] theScopes) {
331                if (theScopes != null && theScopes.length > 0) {
332                        theForm.add("scope", buildScopeString(theScopes));
333                }
334        }
335
336        private static String basicAuth(String theUser, String thePassword) {
337                return "Basic " + Base64.encodeBase64String((theUser + ":" + thePassword).getBytes(StandardCharsets.UTF_8));
338        }
339
340        private static void requireNotBlank(String theValue, String theName) {
341                if (theValue == null || theValue.trim().isEmpty()) {
342                        throw new IllegalArgumentException(theName + " must not be null or empty");
343                }
344        }
345
346        /**
347         * Performs the complete OAuth 2.0 authorization code flow including user login.
348         *
349         * <p>This method orchestrates the entire authorization code flow by:</p>
350         * <ol>
351         *   <li>Obtaining an authorization code through the authorization endpoint</li>
352         *   <li>Exchanging the authorization code for an access token</li>
353         * </ol>
354         *
355         * <p>The method handles both confidential clients (with secret) and public clients (without secret).</p>
356         *
357         * @param clientId the OAuth 2.0 client identifier. Must not be null.
358         * @param redirectUri the redirect URI for receiving the authorization code. Must not be null.
359         * @param theScopes array of requested OAuth 2.0 scopes. Must not be null.
360         * @param state the state parameter for CSRF protection. May be null.
361         * @param theSecret the client secret. If null, the client is treated as public.
362         * @return the access token as a string
363         * @throws IOException if any HTTP communication or response parsing fails
364         * @see #getAuthorizationCode(String, String, String[], String, String, String)
365         * @see #exchangeCode(String, String, String)
366         * @see #exchangeCodeWithSecret(String, String,String,  String, boolean)
367         */
368        public String performAuthorizationCodeFlow(
369                        String clientId,
370                        String redirectUri,
371                        String[] theScopes,
372                        String state,
373                        String theSecret,
374                        String theUsername,
375                        String thePassword)
376                        throws IOException {
377                String code = getAuthorizationCode(clientId, redirectUri, theScopes, state, theUsername, thePassword);
378                String token;
379                if (theSecret != null) {
380                        token = exchangeCodeWithSecret(clientId, theSecret, code, redirectUri, true);
381                } else {
382                        token = exchangeCode(clientId, code, redirectUri);
383                }
384                return token;
385        }
386
387        /**
388         * Attempts to access an authorization URL and handles the redirect to the login screen.
389         *
390         * <p>This method makes a GET request to the authorization endpoint and expects to receive
391         * a redirect response (302/303) that points to the login screen. This is part of the normal
392         * OAuth 2.0 flow when the user is not yet authenticated.</p>
393         *
394         * @param theRequestUrl the authorization URL to request. Must not be null.
395         * @return the login screen URL extracted from the Location header of the redirect response
396         * @throws IOException if the request URL doesn't redirect to the expected signin location
397         * @throws RestClientException if the response is not a redirect (302/303) or if the Location header is missing
398         */
399        public String authorizeBeforeLogin(String theRequestUrl) throws IOException {
400                String signinLocation = "";
401
402                ResponseEntity<String> retrieve =
403                                myRestClient.get().uri(theRequestUrl).retrieve().toEntity(String.class);
404
405                if (retrieve.getStatusCode().value() == 302 || retrieve.getStatusCode().value() == 303) {
406                        URI uri = retrieve.getHeaders().getLocation();
407                        if (uri != null) {
408                                signinLocation = uri.toString();
409                                if (!signinLocation.startsWith(mySmartRootUrl + "/signin")) {
410                                        throw new IOException("Expected redirect to signin but got: " + signinLocation);
411                                }
412                        }
413                } else {
414                        throw new RestClientException("Expected 3XX redirect but got " + retrieve.getStatusCode());
415                }
416                return signinLocation;
417        }
418        /**
419         * Obtains an authorization code through the OAuth 2.0 authorization flow.
420         *
421         * <p>This method performs the first part of the authorization code flow:</p>
422         * <ol>
423         *   <li>Constructs the authorization URL with the provided parameters</li>
424         *   <li>Follows redirects to the login screen</li>
425         *   <li>Performs login</li>
426         *   <li>Completes the authorization and extracts the authorization code</li>
427         * </ol>
428         *
429         * <p>The authorization code can then be exchanged for tokens using
430         * {@link #exchangeCode(String, String,String )} or related methods.</p>
431         *
432         * @param clientId the OAuth 2.0 client identifier. Must not be null.
433         * @param redirectUri the redirect URI for receiving the authorization code. Must not be null.
434         * @param theScopes array of requested OAuth 2.0 scopes. Must not be null.
435         * @param state the state parameter for CSRF protection. May be null.
436         * @return the authorization code as a string
437         * @throws IOException if any HTTP communication fails or if the authorization code cannot be extracted
438         * @see #performAuthorizationCodeFlow(String, String, String[], String, String, String, String)
439         */
440        public String getAuthorizationCode(
441                        String clientId,
442                        String redirectUri,
443                        String[] theScopes,
444                        String state,
445                        String theUsername,
446                        String thePassword)
447                        throws IOException {
448                String scopes = buildScopeString(theScopes);
449
450                String requestUrl = UriComponentsBuilder.fromPath("/oauth/authorize")
451                                .queryParam("response_type", "code")
452                                .queryParam("scope", scopes)
453                                .queryParam("client_id", clientId)
454                                .queryParam("state", state)
455                                .queryParam("redirect_uri", redirectUri)
456                                .toUriString();
457
458                // First, attempt the authorize call, and get bounced.
459                authorizeBeforeLogin(requestUrl);
460
461                String nextUrl = loginWithPassword(theUsername, thePassword);
462                return authorizeAfterLogin(nextUrl);
463        }
464
465        /**
466         * Builds a space-separated scope string from an array of scopes.
467         *
468         * <p>This utility method converts an array of OAuth 2.0 scope strings into a single
469         * space-separated string as required by the OAuth 2.0 specification.</p>
470         *
471         * @param theScopes array of OAuth 2.0 scopes. Must not be null.
472         * @return space-separated scope string, or empty string if no scopes provided
473         */
474        public String buildScopeString(String[] theScopes) {
475                List<String> scopeList = Arrays.stream(theScopes).toList();
476                String scopes = "";
477
478                if (!scopeList.isEmpty()) {
479                        scopes = String.join(" ", scopeList);
480                }
481                return scopes;
482        }
483
484        /**
485         * Exchanges an authorization code for an access token (public client).
486         *
487         * <p>This is a convenience method for public clients that don't have a client secret.
488         * It delegates to {@link #exchangeCodeWithSecret(String, String, String, String)} with
489         * a null client secret.</p>
490         *
491         * @param theClientId the OAuth 2.0 client identifier. Must not be null.
492         * @param theCode the authorization code to exchange. Must not be null.
493         * @return the access token as a string
494         * @throws IOException if the token exchange request fails
495         * @see #exchangeCodeWithSecret(String, String, String, String)
496         */
497        public String exchangeCode(String theClientId, String theCode, String theRedirectUri) throws IOException {
498                return exchangeCodeWithSecret(theClientId, null, theCode, theRedirectUri);
499        }
500
501        /**
502         * Exchanges an authorization code for an access token using HTTP Basic authentication.
503         *
504         * <p>This is a convenience method that delegates to
505         * {@link #exchangeCodeWithSecret(String, String, String, String, boolean)} with
506         * the secret_as_param flag set to false, meaning the client secret will be sent
507         * in the Authorization header using HTTP Basic authentication.</p>
508         *
509         * @param theClientId the OAuth 2.0 client identifier. Must not be null.
510         * @param theClientSecret the client secret. If null, no authentication is performed.
511         * @param theCode the authorization code to exchange. Must not be null.
512         * @return the access token as a string
513         * @throws IOException if the token exchange request fails
514         * @see #exchangeCodeWithSecret(String, String,String, String, boolean)
515         */
516        public String exchangeCodeWithSecret(
517                        String theClientId, String theClientSecret, String theCode, String theRedirectUri) throws IOException {
518                return exchangeCodeWithSecret(theClientId, theClientSecret, theCode, theRedirectUri, false);
519        }
520
521        /**
522         * Completes the authorization step and extracts the authorization code from the redirect.
523         *
524         * <p>This method makes a request to the authorization URL (after user login) and expects
525         * to receive a redirect response containing the authorization code. The authorization code
526         * is extracted from the callback URL in the Location header.</p>
527         *
528         * @param theAuthorizeUrl the authorization URL to request (typically received after login). Must not be null.
529         * @return the authorization code extracted from the redirect URL
530         * @throws IOException if the authorization code cannot be found in the redirect URL
531         * @throws RestClientException if the response is not a redirect (302/303) or if the Location header is missing
532         * @see #extractCodeFromUrl(String)
533         */
534        public String authorizeAfterLogin(String theAuthorizeUrl) throws IOException {
535                String code;
536                ResponseEntity<String> resp =
537                                myRestClient.get().uri(theAuthorizeUrl).retrieve().toEntity(String.class);
538                theAuthorizeUrl = expectRedirectAndGetLocationHeaderValue(resp);
539                code = extractCodeFromUrl(theAuthorizeUrl);
540                return code;
541        }
542
543        private String expectRedirectAndGetLocationHeaderValue(ResponseEntity<String> resp) {
544                if (!(resp.getStatusCode().value() == 302 || resp.getStatusCode().value() == 303)) {
545                        throw new RestClientException("Expected redirect response (302/303) but got: "
546                                        + resp.getStatusCode().value());
547                }
548                URI uri = resp.getHeaders().getLocation();
549                if (uri != null) {
550                        return uri.toString();
551                } else {
552                        throw new RestClientException("During redirect, the Location header was missing!");
553                }
554        }
555
556        /**
557         * Extracts the authorization code from a callback URL.
558         *
559         * <p>This utility method parses the authorization code from the "code" query parameter
560         * in an OAuth 2.0 callback URL. This is typically used when processing the redirect
561         * response from the authorization server.</p>
562         *
563         * @param theUrl the callback URL containing the authorization code parameter. Must not be null.
564         * @return the authorization code value
565         * @throws IOException if the authorization code parameter is not found in the URL
566         */
567        public static String extractCodeFromUrl(String theUrl) throws IOException {
568                if (theUrl == null || theUrl.trim().isEmpty()) {
569                        throw new IllegalArgumentException("theUrl must not be null or empty");
570                }
571
572                String code;
573                int start = theUrl.indexOf("code=");
574                if (start == -1) {
575                        throw new IOException("Could not find authorization code in redirect URL: " + theUrl);
576                }
577
578                int codeStart = start + "code=".length();
579                int end = theUrl.indexOf('&', start);
580                if (end == -1) {
581                        // No more parameters after code, use end of string
582                        end = theUrl.length();
583                }
584
585                code = theUrl.substring(codeStart, end);
586                return code;
587        }
588
589        /**
590         * Fetches the login screen and extracts the CSRF token.
591         *
592         * <p>This method retrieves the SMART login page and parses the HTML to extract
593         * the CSRF token required for form-based authentication. The CSRF token is
594         * embedded in a hidden form field and is required to prevent cross-site request forgery attacks.</p>
595         *
596         * @return the CSRF token extracted from the login screen HTML
597         * @throws IOException if an error occurs while fetching the login screen or if the expected
598         *                     login page content is not found
599         * @see WebTestUtil#extractCsrfToken(String)
600         */
601        private String fetchCsrfTokenFromLoginScreen() throws IOException {
602                String respString = myRestClient.get().uri("/signin").retrieve().body(String.class);
603
604                ourLog.debug("Response: {}", respString);
605                if (respString == null || !respString.contains("<title>Login to SMART Application</title>")) {
606                        throw new IOException("Response does not contain expected login page title");
607                }
608
609                return WebTestUtil.extractCsrfToken(respString);
610        }
611
612        /**
613         * Performs form-based login with username and password credentials.
614         *
615         * <p>This method handles the complete login process:</p>
616         * <ol>
617         *   <li>Fetches the login page and extracts the CSRF token</li>
618         *   <li>Submits the login form with credentials and CSRF token</li>
619         *   <li>Follows the redirect response to get the next URL in the flow</li>
620         * </ol>
621         *
622         * @param theUser the username for authentication. Must not be null.
623         * @param thePassword the password for authentication. Must not be null.
624         * @return the URL to redirect to after successful login (typically the authorization endpoint)
625         * @throws IOException if the login request fails or if the expected redirect response is not received
626         * @throws RestClientException if the HTTP response status is not a redirect (302/303)
627         */
628        public String loginWithPassword(String theUser, String thePassword) throws IOException {
629                String csrfToken = fetchCsrfTokenFromLoginScreen();
630                String formData = "username=" + theUser + "&password=" + thePassword + "&_csrf=" + csrfToken;
631
632                ResponseEntity<String> response = myRestClient
633                                .post()
634                                .uri("/authenticate")
635                                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
636                                .body(formData)
637                                .retrieve()
638                                .toEntity(String.class);
639
640                return expectRedirectAndGetLocationHeaderValue(response);
641        }
642}