diff --git a/CodenameOne/src/com/codename1/io/oidc/OidcClient.java b/CodenameOne/src/com/codename1/io/oidc/OidcClient.java index 7032ed78a09..94744df115e 100644 --- a/CodenameOne/src/com/codename1/io/oidc/OidcClient.java +++ b/CodenameOne/src/com/codename1/io/oidc/OidcClient.java @@ -117,6 +117,14 @@ public final class OidcClient { private String clientId; private String clientSecret; private String redirectUri; + /// The IPv4 loopback address a loopback redirect URI may name (RFC 8252, section 7.3). + private static final String LOOPBACK_ADDRESS = "127.0.0.1"; // NOPMD AvoidUsingHardCodedIP - the loopback interface, by definition + private String loopbackRedirectUri; + private String loopbackHost; + private int loopbackPort; + private String loopbackPath; + /// How long a loopback sign-in waits for the browser to come back. A test shortens it. + long loopbackTimeoutMillis = 10L * 60L * 1000L; private String[] scopes; private String[] additionalAuthParams = new String[0]; private String[] additionalTokenParams = new String[0]; @@ -240,6 +248,65 @@ public OidcClient setRedirectUri(String redirectUri) { return this; } + /// Signs in through the user's default browser on platforms that can + /// listen on the loopback interface -- JavaSE, so the simulator and + /// desktop apps -- instead of an in-app window, as command-line tools do + /// (RFC 8252 section 7.3). [#authorize()] listens on `127.0.0.1`, opens + /// the browser, and the provider redirects it back to this URI with the + /// port the listener bound. Elsewhere, and where + /// [SystemBrowser#isLoopbackAvailable()] is `false`, [#setRedirectUri(String)] + /// is used as before. + /// + /// The provider must accept a loopback redirect for this client, on any + /// port when the URI names none. Some do not accept one for a client + /// registered as a mobile app, so this is off until it is set. + /// + /// #### Parameters + /// + /// - `loopbackRedirectUri`: `http://127.0.0.1/` or + /// `http://localhost/`, optionally with a port, and with no + /// query or fragment. `null` turns the loopback sign-in off. + /// + /// #### Throws + /// + /// - `IllegalArgumentException`: if the URI is not such an address. + public OidcClient setLoopbackRedirectUri(String loopbackRedirectUri) { + if (loopbackRedirectUri == null) { + this.loopbackRedirectUri = null; + return this; + } + String prefix = "http://"; + if (!loopbackRedirectUri.startsWith(prefix) || loopbackRedirectUri.indexOf('?') >= 0 + || loopbackRedirectUri.indexOf('#') >= 0) { + throw new IllegalArgumentException("A loopback redirect URI is http://127.0.0.1/ " + + "or http://localhost/, with no query or fragment: " + loopbackRedirectUri); + } + String rest = loopbackRedirectUri.substring(prefix.length()); + int slash = rest.indexOf('/'); + String authority = slash < 0 ? rest : rest.substring(0, slash); + String path = slash < 0 ? "/" : rest.substring(slash); + int colon = authority.indexOf(':'); + String host = colon < 0 ? authority : authority.substring(0, colon); + int port = 0; + if (colon >= 0) { + try { + port = Integer.parseInt(authority.substring(colon + 1)); + } catch (NumberFormatException e) { + port = -1; + } + } + if (!(LOOPBACK_ADDRESS.equals(host) || "localhost".equalsIgnoreCase(host)) || port < 0 || port > 65535 + || (colon >= 0 && port == 0)) { + throw new IllegalArgumentException("A loopback redirect URI is http://127.0.0.1/ " + + "or http://localhost/, with no query or fragment: " + loopbackRedirectUri); + } + this.loopbackRedirectUri = loopbackRedirectUri; + this.loopbackHost = host; + this.loopbackPort = port; + this.loopbackPath = path; + return this; + } + public OidcClient setScopes(String... scopes) { if (scopes == null) { this.scopes = null; @@ -342,12 +409,19 @@ public OidcClient setResponseMode(String mode) { /// the token set or errors with [OidcException] (e.g. `USER_CANCELLED`, /// `STATE_MISMATCH`). public AsyncResource authorize() { + if (loopbackRedirectUri != null) { + OidcLoopbackRedirect loopback = SystemBrowser.getLoopbackProvider(); + if (loopback != null && loopback.isSupported()) { + requireClient(); + return authorizeLoopback(loopback); + } + } requireConfigured(); final AsyncResource out = new AsyncResource(); final PkceChallenge pkce = PkceChallenge.generate(); final String state = Util.randomToken(16); final String nonce = Util.randomToken(16); - String authUrl = buildAuthorizationUrl(state, nonce, pkce); + String authUrl = buildAuthorizationUrl(redirectUri, state, nonce, pkce); SystemBrowser.authenticate(authUrl, redirectUri) .ready(new SuccessCallback() { @Override @@ -364,6 +438,97 @@ public void onSucess(Throwable err) { return out; } + /// [#authorize()] through the default browser: listen, send the browser + /// to the provider, wait for it to come back, then exchange the code + /// with the redirect URI the listener answered. + private AsyncResource authorizeLoopback(final OidcLoopbackRedirect loopback) { + final LoopbackSignIn out = new LoopbackSignIn(); + final PkceChallenge pkce = PkceChallenge.generate(); + final String state = Util.randomToken(16); + final String nonce = Util.randomToken(16); + final String host = loopbackHost; + final int port = loopbackPort; + final String path = loopbackPath; + final long timeout = loopbackTimeoutMillis; + Runnable task = new Runnable() { + @Override + public void run() { + final OidcLoopbackRedirect.Listener listener; + try { + listener = loopback.listen(host, port, path); + } catch (Throwable t) { + out.error(new OidcException(OidcException.TRANSPORT_ERROR, + "Couldn't listen for the sign-in on " + host + ": " + t.getMessage(), t)); + return; + } + if (!out.attach(listener)) { + return; + } + final String redirect = listener.getRedirectUri(); + String result; + try { + result = listener.await(buildAuthorizationUrl(redirect, state, nonce, pkce), timeout); + } catch (Throwable t) { + out.error(new OidcException(OidcException.TRANSPORT_ERROR, + "The sign-in in the browser failed: " + t.getMessage(), t)); + return; + } finally { + listener.close(); + } + if (out.isDone()) { + return; + } + if (result == null) { + out.error(new OidcException(OidcException.USER_CANCELLED, + "The sign-in in the browser didn't finish")); + return; + } + final String redirectUrl = result; + CN.callSerially(new Runnable() { + @Override + public void run() { + handleRedirect(redirectUrl, redirect, state, nonce, pkce, out); + } + }); + } + }; + new Thread(task, "OidcLoopback").start(); + return out; + } + + /// A loopback sign-in's result. Cancelling it stops its listener, which + /// ends the wait for the browser: [AsyncResource#cancel(boolean)] runs no + /// callbacks, so the listener is closed here. + private static final class LoopbackSignIn extends AsyncResource { + private OidcLoopbackRedirect.Listener listener; + + /// Keeps `l` to close on cancel. Returns `false`, having closed it, + /// when the sign-in was cancelled before it started listening. + boolean attach(OidcLoopbackRedirect.Listener l) { + synchronized (this) { + if (!isCancelled()) { + listener = l; + return true; + } + } + l.close(); + return false; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + boolean cancelled = super.cancel(mayInterruptIfRunning); + OidcLoopbackRedirect.Listener l; + synchronized (this) { + l = listener; + } + if (l != null) { + l.close(); + } + return cancelled; + } + } + /// Exchanges a stored refresh token for a fresh access token. Pass the /// value returned from [OidcTokens#getRefreshToken()] on a previous flow. /// The stored session supplies the original subject for any refreshed ID token. @@ -890,12 +1055,16 @@ private void tellTokenListener(OidcTokens tokens) { // internals private void requireConfigured() { - if (clientId == null) { - throw new IllegalStateException("clientId is required"); - } + requireClient(); if (redirectUri == null) { throw new IllegalStateException("redirectUri is required"); } + } + + private void requireClient() { + if (clientId == null) { + throw new IllegalStateException("clientId is required"); + } if (configuration.getAuthorizationEndpoint() == null) { throw new IllegalStateException("authorizationEndpoint missing from configuration"); } @@ -912,12 +1081,12 @@ private String storageKey() { return issuer + "|" + clientId; } - private String buildAuthorizationUrl(String state, String nonce, PkceChallenge pkce) { + private String buildAuthorizationUrl(String redirect, String state, String nonce, PkceChallenge pkce) { StringBuilder b = new StringBuilder(configuration.getAuthorizationEndpoint()); b.append(configuration.getAuthorizationEndpoint().indexOf('?') >= 0 ? '&' : '?'); appendParam(b, "response_type", "code"); appendParam(b, "client_id", clientId); - appendParam(b, "redirect_uri", redirectUri); + appendParam(b, "redirect_uri", redirect); if (scopes != null && scopes.length > 0) { appendParam(b, "scope", join(scopes)); } @@ -949,6 +1118,18 @@ void handleRedirect(String redirectUrl, String expectedNonce, PkceChallenge pkce, final AsyncResource out) { + handleRedirect(redirectUrl, redirectUri, expectedState, expectedNonce, pkce, out); + } + + /// Reads the authorization response that arrived at `redirect`, and + /// exchanges its code with that same redirect URI, as the token endpoint + /// requires (RFC 6749 section 4.1.3). + void handleRedirect(String redirectUrl, + String redirect, + String expectedState, + String expectedNonce, + PkceChallenge pkce, + final AsyncResource out) { Map params = parseRedirectParams(redirectUrl); // Before anything the response says is believed, who it says it is from (RFC 9207). // A response another provider produced -- one this app also signs in with, and an @@ -992,10 +1173,11 @@ void handleRedirect(String redirectUrl, "Authorization redirect was missing the 'code' parameter")); return; } - exchangeCode(code, expectedNonce, pkce, out); + exchangeCode(code, redirect, expectedNonce, pkce, out); } private void exchangeCode(String code, + String redirect, final String expectedNonce, PkceChallenge pkce, final AsyncResource out) { @@ -1007,7 +1189,7 @@ private void exchangeCode(String code, Map args = new HashMap(); args.put("grant_type", "authorization_code"); args.put("code", code); - args.put("redirect_uri", redirectUri); + args.put("redirect_uri", redirect); args.put("code_verifier", pkce.getVerifier()); appendBaseTokenArgs(args); postToTokenEndpoint(args, null, expectedNonce, out); diff --git a/CodenameOne/src/com/codename1/io/oidc/OidcLoopbackRedirect.java b/CodenameOne/src/com/codename1/io/oidc/OidcLoopbackRedirect.java new file mode 100644 index 00000000000..e734461c23a --- /dev/null +++ b/CodenameOne/src/com/codename1/io/oidc/OidcLoopbackRedirect.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2012-2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.io.oidc; + +import java.io.IOException; + +/// Service-provider interface that [SystemBrowser] uses to sign in through the +/// user's own browser on a desktop, as command-line tools do: the app listens +/// on the loopback interface, opens the default browser at the authorization +/// URL, and the identity provider redirects the browser to +/// `http://127.0.0.1:/` (RFC 8252 section 7.3). +/// +/// The JavaSE port (the simulator and desktop apps) registers one through +/// [SystemBrowser#setLoopbackProvider(OidcLoopbackRedirect)]. [OidcClient] +/// uses it when the application has set +/// [OidcClient#setLoopbackRedirectUri(String)]. +public interface OidcLoopbackRedirect { + + /// `true` if this implementation can listen on the loopback interface + /// and open a browser on the current machine. + boolean isSupported(); + + /// Starts listening on `127.0.0.1` for one request to `path`. + /// + /// #### Parameters + /// + /// - `host`: The host written in the redirect URI, `127.0.0.1` or + /// `localhost`. The listener binds `127.0.0.1` either way. + /// + /// - `port`: The port to listen on, or 0 for any free port. + /// + /// - `path`: The redirect URI's path, starting with `/`. + /// + /// #### Returns + /// + /// A listener whose [Listener#getRedirectUri()] names the port it bound. + Listener listen(String host, int port, String path) throws IOException; + + /// One sign-in's listener. + interface Listener { + + /// The redirect URI this listener answers, with the port it bound, + /// for example `http://127.0.0.1:53817/oauth2redirect`. + String getRedirectUri(); + + /// Opens the default browser at `authUrl` and blocks until the + /// browser is redirected to [#getRedirectUri()]. Answers that request + /// with a page telling the user to return to the app. + /// + /// #### Returns + /// + /// The full redirect URL, including its query, or `null` if + /// [#close()] was called or `timeoutMillis` passed first. + String await(String authUrl, long timeoutMillis) throws IOException; + + /// Stops listening. Safe to call more than once, from any thread. + void close(); + } +} diff --git a/CodenameOne/src/com/codename1/io/oidc/SystemBrowser.java b/CodenameOne/src/com/codename1/io/oidc/SystemBrowser.java index bab27960030..2c7a29b1e01 100644 --- a/CodenameOne/src/com/codename1/io/oidc/SystemBrowser.java +++ b/CodenameOne/src/com/codename1/io/oidc/SystemBrowser.java @@ -30,10 +30,19 @@ import com.codename1.util.AsyncResource; /// Routes an authorization-code-flow sign-in through the *system browser* -/// (`ASWebAuthenticationSession` on iOS, an Android Custom Tab on Android, -/// the user's default browser on JavaSE / Web) and resolves with the final -/// redirect URL once the OS hands it back. Replaces the embedded WebView -/// approach used by the legacy [com.codename1.io.Oauth2] class. +/// (`ASWebAuthenticationSession` on iOS, an Android Custom Tab on Android) +/// and resolves with the final redirect URL once the OS hands it back. +/// Replaces the embedded WebView approach used by the legacy +/// [com.codename1.io.Oauth2] class. +/// +/// Where no port registers a provider -- JavaSE (the simulator and desktop +/// apps) and the web -- [#authenticate(String, String)] opens an in-app +/// [BrowserWindow] instead; on JavaSE that window is a JavaFX web view. +/// JavaSE can sign in through the user's default browser instead, as +/// command-line tools do, with a loopback redirect +/// (`http://127.0.0.1:/`): [OidcClient] does this when the +/// application sets [OidcClient#setLoopbackRedirectUri(String)], through the +/// provider the port registers with [#setLoopbackProvider(OidcLoopbackRedirect)]. /// /// You normally do not call this directly -- [OidcClient#authorize()] does it /// for you. Use the public methods on this class when wiring up a custom @@ -56,6 +65,10 @@ public final class SystemBrowser { /// the synchronization itself. private static OidcBrowserNative provider; + /// Port-supplied loopback implementation (JavaSE), or `null`. Guarded + /// like [#provider]. + private static OidcLoopbackRedirect loopbackProvider; + private SystemBrowser() {} /// `true` when a native, OS-level implementation is available on the @@ -82,6 +95,29 @@ public static void setProvider(OidcBrowserNative p) { } } + /// Registers the [OidcLoopbackRedirect] that signs in through the + /// default browser with a loopback redirect. Called at start-up by the + /// JavaSE port. Pass `null` to remove it. + public static void setLoopbackProvider(OidcLoopbackRedirect p) { + synchronized (SystemBrowser.class) { + loopbackProvider = p; + } + } + + /// `true` when this platform can sign in through the default browser + /// with a loopback redirect, so [OidcClient#setLoopbackRedirectUri(String)] + /// takes effect. + public static boolean isLoopbackAvailable() { + OidcLoopbackRedirect l = getLoopbackProvider(); + return l != null && l.isSupported(); + } + + static OidcLoopbackRedirect getLoopbackProvider() { + synchronized (SystemBrowser.class) { + return loopbackProvider; + } + } + private static OidcBrowserNative getProvider() { synchronized (SystemBrowser.class) { return provider; diff --git a/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEOidcLoopbackRedirect.java b/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEOidcLoopbackRedirect.java new file mode 100644 index 00000000000..27aada633da --- /dev/null +++ b/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEOidcLoopbackRedirect.java @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2012-2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl.javase; + +import com.codename1.io.oidc.OidcLoopbackRedirect; +import java.awt.GraphicsEnvironment; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketTimeoutException; + +/** + * Signs in through the user's default browser with a loopback redirect + * (RFC 8252 section 7.3), as command-line tools do: listens on + * {@code 127.0.0.1}, opens the browser at the authorization URL, and answers + * the provider's redirect with a page telling the user to go back to the app. + * The JavaSE port registers it with + * {@link com.codename1.io.oidc.SystemBrowser#setLoopbackProvider(OidcLoopbackRedirect)}. + */ +public class JavaSEOidcLoopbackRedirect implements OidcLoopbackRedirect { + + /** Opens a URL in the default browser. */ + public interface Browser { + void open(String url) throws Exception; + } + + /** The longest request head read; anything longer is refused. */ + static final int MAX_HEAD = 16 * 1024; + + private final Browser browser; + + public JavaSEOidcLoopbackRedirect(Browser browser) { + this.browser = browser; + } + + @Override + public boolean isSupported() { + return !GraphicsEnvironment.isHeadless(); + } + + @Override + public Listener listen(String host, int port, String path) throws IOException { + ServerSocket server = new ServerSocket(); + try { + server.bind(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), port), 8); + } catch (IOException e) { + server.close(); + throw e; + } + return new LoopbackListener(server, host, path, browser); + } + + static final class LoopbackListener implements Listener { + private final ServerSocket server; + private final String origin; + private final String path; + private final Browser browser; + private volatile boolean closed; + + LoopbackListener(ServerSocket server, String host, String path, Browser browser) { + this.server = server; + this.origin = "http://" + host + ":" + server.getLocalPort(); + this.path = path; + this.browser = browser; + } + + @Override + public String getRedirectUri() { + return origin + path; + } + + @Override + public String await(String authUrl, long timeoutMillis) throws IOException { + try { + browser.open(authUrl); + } catch (Exception e) { + throw new IOException("Couldn't open the browser: " + e.getMessage(), e); + } + long deadline = System.currentTimeMillis() + timeoutMillis; + server.setSoTimeout(250); + while (!closed) { + if (System.currentTimeMillis() >= deadline) { + return null; + } + Socket socket; + try { + socket = server.accept(); + } catch (SocketTimeoutException tick) { + continue; + } catch (IOException e) { + if (closed) { + return null; + } + throw e; + } + try { + String target = answer(socket); + if (target != null) { + return origin + target; + } + } catch (IOException oneBadRequest) { + // A request that breaks off is not the redirect; keep listening. + } finally { + socket.close(); + } + } + return null; + } + + /** + * Reads one request and answers it. Returns its target when it is + * the redirect (a GET to the path), else null. + */ + String answer(Socket socket) throws IOException { + socket.setSoTimeout(5000); + String target = requestTarget(socket.getInputStream()); + OutputStream out = socket.getOutputStream(); + if (target == null) { + respond(out, "404 Not Found", "Not found."); + return null; + } + boolean failed = target.indexOf("?error=") >= 0 || target.indexOf("&error=") >= 0; + respond(out, "200 OK", failed + ? page("Sign-in didn't finish", "Go back to the app to see why. You can close this tab.") + : page("You can close this tab", "Go back to the app to continue.")); + return target; + } + + /** The target of a GET to {@link #path}, or null for anything else. */ + String requestTarget(InputStream in) throws IOException { + String line = firstLine(readHead(in)); + if (line == null || !line.startsWith("GET ")) { + return null; + } + int end = line.indexOf(' ', 4); + if (end < 0) { + return null; + } + String target = line.substring(4, end); + int q = target.indexOf('?'); + String p = q < 0 ? target : target.substring(0, q); + return p.equals(path) ? target : null; + } + + @Override + public void close() { + closed = true; + try { + server.close(); + } catch (IOException ignored) { + // Closing is best effort; the socket is gone either way. + } + } + } + + static String readHead(InputStream in) throws IOException { + ByteArrayOutputStream head = new ByteArrayOutputStream(); + int matched = 0; + while (head.size() < MAX_HEAD) { + int b = in.read(); + if (b < 0) { + break; + } + head.write(b); + matched = (b == (matched % 2 == 0 ? '\r' : '\n')) ? matched + 1 : (b == '\r' ? 1 : 0); + if (matched == 4) { + break; + } + } + return new String(head.toByteArray(), "ISO-8859-1"); + } + + static String firstLine(String head) { + int end = head.indexOf("\r\n"); + return end < 0 ? null : head.substring(0, end); + } + + static String page(String heading, String text) { + return "" + + "" + + "" + heading + "" + + "" + + "

" + heading + "

" + text + "

"; + } + + private static void respond(OutputStream out, String status, String body) throws IOException { + byte[] bytes = body.getBytes("UTF-8"); + String head = "HTTP/1.1 " + status + "\r\n" + + "Content-Type: text/html; charset=utf-8\r\n" + + "Content-Length: " + bytes.length + "\r\n" + + "Cache-Control: no-store\r\n" + + "Referrer-Policy: no-referrer\r\n" + + "Connection: close\r\n\r\n"; + out.write(head.getBytes("ISO-8859-1")); + out.write(bytes); + out.flush(); + } +} diff --git a/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java b/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java index d53fa531014..431aa176038 100644 --- a/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java +++ b/Ports/JavaSE/src/com/codename1/impl/javase/JavaSEPort.java @@ -12535,6 +12535,16 @@ public void init(Object m) { // com.codename1.mcp.MCP. MCPStdioTransport.register(); MCPSocketTransport.register(); + + // OidcClient.setLoopbackRedirectUri: sign in through the default + // browser with a loopback redirect instead of an in-app window. + com.codename1.io.oidc.SystemBrowser.setLoopbackProvider(new JavaSEOidcLoopbackRedirect( + new JavaSEOidcLoopbackRedirect.Browser() { + @Override + public void open(String url) { + execute(url); + } + })); // The simulator's own tools (keyboard, real-path touches, recording) sit // beside the core ui_* tools on the shared server. getKeyboardController(); diff --git a/docs/developer-guide/Authentication-And-Identity.asciidoc b/docs/developer-guide/Authentication-And-Identity.asciidoc index 9984242680e..975b4377290 100644 --- a/docs/developer-guide/Authentication-And-Identity.asciidoc +++ b/docs/developer-guide/Authentication-And-Identity.asciidoc @@ -6,7 +6,7 @@ This chapter covers Codename One's modern sign-in stack: OpenID Connect, Sign in The stack is rebuilt around two new primitives: * `com.codename1.io.oidc.OidcClient` -- a full OpenID Connect / OAuth 2.0 client with PKCE, discovery, refresh and token persistence. -* `com.codename1.io.oidc.SystemBrowser` -- routes the sign-in step through the platform's hardened sign-in surface where one exists: `ASWebAuthenticationSession` on iOS and Android Custom Tabs. Elsewhere it falls back to `BrowserWindow`, and what that means differs: the Web port opens a real top-level browser window, while JavaSE renders a JavaFX `WebView` inside the app. The desktop one is an embedded view, so a provider that blocks those can refuse a simulator sign-in that works on a device. The Web one has a constraint of its own -- it's a `window.open()` call, and it happens after the discovery request comes back rather than inside the click that started the sign-in, so a browser that has already expired the transient activation blocks it. Tell your users to allow popups for the site, or start the flow from an `OidcClient` you configured ahead of time instead of `discover()`. And point the redirect URI at a page on the app's own origin: the port watches the popup by reading its location, the same-origin policy blocks that read once the popup navigates elsewhere, and the fallback reports the authorization URL again -- so a callback hosted anywhere else never gets recognized and `authorize()` simply never completes. That applies to Apple's `form_post` bridge too, which has to live on that origin rather than beside the Services ID. +* `com.codename1.io.oidc.SystemBrowser` -- routes the sign-in step through the platform's hardened sign-in surface where one exists: `ASWebAuthenticationSession` on iOS and Android Custom Tabs. Elsewhere it falls back to `BrowserWindow` -- unless JavaSE signs in through the user's own browser, as "Picking a redirect URI" below describes -- and what that means differs: the Web port opens a real top-level browser window, while JavaSE renders a JavaFX `WebView` inside the app. The desktop one is an embedded view, so a provider that blocks those can refuse a simulator sign-in that works on a device. The Web one has a constraint of its own -- it's a `window.open()` call, and it happens after the discovery request comes back rather than inside the click that started the sign-in, so a browser that has already expired the transient activation blocks it. Tell your users to allow popups for the site, or start the flow from an `OidcClient` you configured ahead of time instead of `discover()`. And point the redirect URI at a page on the app's own origin: the port watches the popup by reading its location, the same-origin policy blocks that read once the popup navigates elsewhere, and the fallback reports the authorization URL again -- so a callback hosted anywhere else never gets recognized and `authorize()` simply never completes. That applies to Apple's `form_post` bridge too, which has to live on that origin rather than beside the Services ID. Every provider-specific class is a thin layer on top of these primitives, so once you learn the underlying client you understand the whole stack. @@ -77,6 +77,14 @@ For mobile apps, use a *custom scheme* unique to your app, for example `com.exam For web / simulator runs, use a normal HTTPS URL pointing at a page you control. The Codename One fallback `BrowserWindow` closes as soon as the URL matches. +===== Signing in through the user's own browser on the simulator and desktop + +On JavaSE -- the simulator and desktop apps -- `OidcClient` can sign in through the user's default browser instead of an in-app window, the way command-line tools do. Call `setLoopbackRedirectUri` with an address on the loopback interface, such as `http://127.0.0.1/oauth2redirect`. `authorize()` then listens on `127.0.0.1`, opens the browser at the provider's sign-in page, and the provider redirects the browser back to that address with the port the app chose (RFC 8252, section 7.3). The browser tab then tells the user they can close it. The provider's sign-in page runs in a real browser, with the user's saved passwords and passkeys, and a provider that refuses embedded web views accepts it. + +Keep `setRedirectUri` as well: iOS, Android and the Web port go on using it, and so does JavaSE wherever `SystemBrowser.isLoopbackAvailable()` is false, such as a headless run. Name a port only if the provider insists on an exact match. Without one, any free port is used, and the provider must accept a loopback redirect on any port for your client. Many do for a client registered as a desktop or native app, and some, Google among them, don't for one registered as an Android or iOS app. That's why this is off until you set it. + +Cancelling the `AsyncResource` that `authorize()` returns stops the listener. If the browser never comes back, the sign-in fails with `USER_CANCELLED` after ten minutes. + ===== iOS Add the URL scheme to your Info.plist via the standard build hint: diff --git a/maven/core-unittests/src/test/java/com/codename1/io/oidc/OidcLoopbackTest.java b/maven/core-unittests/src/test/java/com/codename1/io/oidc/OidcLoopbackTest.java new file mode 100644 index 00000000000..721ed86b1e6 --- /dev/null +++ b/maven/core-unittests/src/test/java/com/codename1/io/oidc/OidcLoopbackTest.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2012-2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.io.oidc; + +import com.codename1.io.Util; +import com.codename1.junit.UITestBase; +import com.codename1.testing.TestCodenameOneImplementation; +import com.codename1.util.AsyncResource; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static com.codename1.io.oidc.OidcTestSupport.await; +import static com.codename1.io.oidc.OidcTestSupport.text; +import static com.codename1.io.oidc.OidcTestSupport.tokenJson; +import static com.codename1.io.oidc.OidcTestSupport.utf8; +import static org.junit.jupiter.api.Assertions.*; + +/** + * {@link OidcClient#setLoopbackRedirectUri(String)}: signing in through the + * default browser with a loopback redirect, against a fake + * {@link OidcLoopbackRedirect} and the mock network layer. + */ +public class OidcLoopbackTest extends UITestBase { + + private static final String ISSUER = "https://issuer.example.com"; + private static final String AUTH_EP = ISSUER + "/auth"; + private static final String TOKEN_EP = ISSUER + "/token"; + private static final String BOUND = "http://127.0.0.1:53817/oauth2redirect"; + + private FakeLoopback loopback; + private final List tokenRequests = new ArrayList(); + + @BeforeEach + void install() { + // A connection is kept per URL; another test's token request must not be read here. + TestCodenameOneImplementation.getInstance().clearConnections(); + tokenRequests.clear(); + loopback = new FakeLoopback(); + SystemBrowser.setLoopbackProvider(loopback); + TestCodenameOneImplementation.getInstance().setNetworkMockHandler( + new TestCodenameOneImplementation.NetworkMockHandler() { + public void handle(TestCodenameOneImplementation.TestConnection c) { + String body = text(c.getOutputData()); + c.clearRequest(); + if (c.getUrl().startsWith(TOKEN_EP)) { + if (body.length() > 0) { + tokenRequests.add(body); + } + c.respond(200, "OK", utf8(tokenJson("AT", "RT"))); + } else { + c.respond(404, "Not Found", utf8("")); + } + } + }); + } + + @AfterEach + void uninstall() { + SystemBrowser.setLoopbackProvider(null); + TestCodenameOneImplementation.getInstance().clearNetworkMocks(); + TestCodenameOneImplementation.getInstance().clearConnections(); + } + + private OidcClient client() { + return OidcClient.create(OidcConfiguration.newBuilder() + .issuer(ISSUER) + .authorizationEndpoint(AUTH_EP) + .tokenEndpoint(TOKEN_EP) + .build()) + .setClientId("client-123") + .setScopes("email") + .setTokenStore(new OidcTestSupport.MemoryStore()) + .setLoopbackRedirectUri("http://127.0.0.1/oauth2redirect"); + } + + /** The value of {@code name} in a URL's query or a form body. */ + private static String param(String query, String name) { + int start = query.indexOf('?') + 1; + for (String pair : query.substring(start).split("&")) { + int eq = pair.indexOf('='); + if (eq > 0 && pair.substring(0, eq).equals(name)) { + return Util.decode(pair.substring(eq + 1), "UTF-8", true); + } + } + return null; + } + + @Test + void theBoundPortIsTheRedirectInBothRequests() { + OidcTestSupport.Outcome r = await(client().authorize()); + assertNull(r.error, String.valueOf(r.error)); + assertEquals("AT", r.value.getAccessToken()); + assertEquals("127.0.0.1", loopback.host); + assertEquals(0, loopback.port, "no port named: any free port"); + assertEquals("/oauth2redirect", loopback.path); + assertEquals(BOUND, param(loopback.authUrl, "redirect_uri")); + assertTrue(loopback.authUrl.startsWith(AUTH_EP + "?")); + assertEquals(1, tokenRequests.size(), tokenRequests.toString()); + assertEquals(BOUND, param(tokenRequests.get(0), "redirect_uri"), + "the code is exchanged with the redirect it was issued to"); + assertEquals("the-code", param(tokenRequests.get(0), "code")); + assertTrue(loopback.closed, "the listener stops once the browser is back"); + } + + @Test + void aNamedPortIsListenedOn() { + loopback.bound = "http://localhost:8123/cb"; + OidcClient c = client().setLoopbackRedirectUri("http://localhost:8123/cb"); + assertNull(await(c.authorize()).error); + assertEquals("localhost", loopback.host); + assertEquals(8123, loopback.port); + assertEquals("/cb", loopback.path); + assertEquals("http://localhost:8123/cb", param(tokenRequests.get(0), "redirect_uri")); + } + + @Test + void theStateIsStillChecked() { + loopback.answer = BOUND + "?code=the-code&state=someone-elses"; + OidcTestSupport.Outcome r = await(client().authorize()); + assertEquals(OidcException.STATE_MISMATCH, ((OidcException) r.error).getError()); + assertTrue(tokenRequests.isEmpty(), tokenRequests.toString()); + } + + @Test + void aBrowserThatNeverComesBackIsCancelled() { + loopback.answer = null; + OidcTestSupport.Outcome r = await(client().authorize()); + assertEquals(OidcException.USER_CANCELLED, ((OidcException) r.error).getError()); + assertTrue(loopback.closed); + assertTrue(tokenRequests.isEmpty(), tokenRequests.toString()); + } + + @Test + void aListenerThatCannotBindIsATransportError() { + loopback.listenFailure = new IOException("Address already in use"); + OidcTestSupport.Outcome r = await(client().authorize()); + OidcException e = (OidcException) r.error; + assertEquals(OidcException.TRANSPORT_ERROR, e.getError()); + assertTrue(e.getMessage().contains("Address already in use"), e.getMessage()); + } + + @Test + void cancellingTheSignInStopsTheListener() throws Exception { + loopback.block = true; + AsyncResource out = client().authorize(); + assertTrue(loopback.waiting.await(5, TimeUnit.SECONDS)); + assertTrue(out.cancel(true)); + assertTrue(loopback.closedLatch.await(5, TimeUnit.SECONDS), "cancel closes the listener"); + assertTrue(tokenRequests.isEmpty(), tokenRequests.toString()); + } + + @Test + void withoutALoopbackProviderTheRedirectUriIsRequired() { + SystemBrowser.setLoopbackProvider(null); + assertFalse(SystemBrowser.isLoopbackAvailable()); + final OidcClient c = client(); + IllegalStateException e = assertThrows(IllegalStateException.class, new org.junit.jupiter.api.function.Executable() { + public void execute() { + c.authorize(); + } + }); + assertEquals("redirectUri is required", e.getMessage()); + } + + @Test + void anUnsupportedProviderIsNotUsed() { + loopback.supported = false; + assertFalse(SystemBrowser.isLoopbackAvailable()); + final OidcClient c = client(); + assertThrows(IllegalStateException.class, new org.junit.jupiter.api.function.Executable() { + public void execute() { + c.authorize(); + } + }); + assertNull(loopback.host, "nothing listened"); + } + + @Test + void onlyLoopbackAddressesAreAccepted() { + OidcClient c = client(); + for (String ok : new String[]{"http://127.0.0.1/cb", "http://127.0.0.1:8080/cb", "http://localhost/", + "http://127.0.0.1", "http://LOCALHOST:1/a/b"}) { + assertSame(c, c.setLoopbackRedirectUri(ok), ok); + } + for (final String bad : new String[]{"https://127.0.0.1/cb", "http://example.com/cb", "http://127.0.0.2/cb", + "http://127.0.0.1/cb?x=1", "http://127.0.0.1/cb#f", "http://127.0.0.1:0/cb", + "http://127.0.0.1:99999/cb", "http://127.0.0.1:x/cb", "com.example.app:/cb", + "http://user@127.0.0.1/cb"}) { + final OidcClient d = client(); + assertThrows(IllegalArgumentException.class, new org.junit.jupiter.api.function.Executable() { + public void execute() { + d.setLoopbackRedirectUri(bad); + } + }, bad); + } + assertSame(c, c.setLoopbackRedirectUri(null)); + } + + /** Listens nowhere; answers with the redirect a provider would send. */ + static final class FakeLoopback implements OidcLoopbackRedirect { + boolean supported = true; + IOException listenFailure; + String bound = BOUND; + /** The redirect the browser comes back with; STATE is replaced by the request's state. */ + String answer = BOUND + "?code=the-code&state=STATE"; + boolean block; + final CountDownLatch waiting = new CountDownLatch(1); + final CountDownLatch closedLatch = new CountDownLatch(1); + volatile boolean closed; + String host; + int port = -1; + String path; + String authUrl; + + public boolean isSupported() { + return supported; + } + + public Listener listen(String host, int port, String path) throws IOException { + if (listenFailure != null) { + throw listenFailure; + } + this.host = host; + this.port = port; + this.path = path; + return new Listener() { + public String getRedirectUri() { + return bound; + } + + public String await(String url, long timeoutMillis) throws IOException { + authUrl = url; + waiting.countDown(); + if (block) { + try { + closedLatch.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return null; + } + String a = answer; + if (a == null) { + return null; + } + return a.replace("STATE", String.valueOf(param(url, "state"))) + .replace(BOUND, bound); + } + + public void close() { + closed = true; + closedLatch.countDown(); + } + }; + } + } +} diff --git a/maven/javase/src/test/java/com/codename1/impl/javase/JavaSEOidcLoopbackRedirectTest.java b/maven/javase/src/test/java/com/codename1/impl/javase/JavaSEOidcLoopbackRedirectTest.java new file mode 100644 index 00000000000..8713390bd31 --- /dev/null +++ b/maven/javase/src/test/java/com/codename1/impl/javase/JavaSEOidcLoopbackRedirectTest.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2012-2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl.javase; + +import com.codename1.io.oidc.OidcLoopbackRedirect; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * The JavaSE loopback listener, on real sockets: it answers the provider's + * redirect to its path, ignores everything else, and stops when closed or + * when its time is up. + */ +public class JavaSEOidcLoopbackRedirectTest { + + /** + * A browser that makes the given requests, in order, to the listener's + * port. Like a real one it returns at once and loads on its own thread. + */ + private static final class FakeBrowser implements JavaSEOidcLoopbackRedirect.Browser { + final List opened = new ArrayList(); + final List responses = Collections.synchronizedList(new ArrayList()); + String[] requests = new String[0]; + int port; + Thread loading; + + public void open(String url) { + opened.add(url); + loading = new Thread(new Runnable() { + public void run() { + try { + for (String r : requests) { + responses.add(send(port, r)); + } + } catch (IOException e) { + responses.add("FAILED " + e); + } + } + }); + loading.start(); + } + + void finish() throws InterruptedException { + loading.join(5000); + } + } + + private static String send(int port, String request) throws IOException { + Socket s = new Socket("127.0.0.1", port); + try { + OutputStream out = s.getOutputStream(); + out.write(request.getBytes("ISO-8859-1")); + out.flush(); + InputStream in = s.getInputStream(); + ByteArrayOutputStream b = new ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int n; + while ((n = in.read(buf)) > 0) { + b.write(buf, 0, n); + } + return new String(b.toByteArray(), "UTF-8"); + } finally { + s.close(); + } + } + + private static String get(String target) { + return "GET " + target + " HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"; + } + + @Test + public void theRedirectIsAnsweredAndReturned() throws Exception { + FakeBrowser browser = new FakeBrowser(); + OidcLoopbackRedirect.Listener l = new JavaSEOidcLoopbackRedirect(browser).listen("127.0.0.1", 0, "/cb"); + try { + String uri = l.getRedirectUri(); + assertTrue(uri.matches("http://127\\.0\\.0\\.1:\\d+/cb"), uri); + browser.port = Integer.parseInt(uri.substring("http://127.0.0.1:".length(), uri.length() - 3)); + browser.requests = new String[]{get("/favicon.ico"), "POST /cb HTTP/1.1\r\n\r\n", + get("/cb?code=abc&state=xyz")}; + String result = l.await("https://idp.example/auth?x=1", 5000); + assertEquals(uri + "?code=abc&state=xyz", result); + browser.finish(); + assertEquals("https://idp.example/auth?x=1", browser.opened.get(0)); + assertTrue(browser.responses.get(0).startsWith("HTTP/1.1 404"), browser.responses.get(0)); + assertTrue(browser.responses.get(1).startsWith("HTTP/1.1 404"), "only a GET is the redirect"); + String page = browser.responses.get(2); + assertTrue(page.startsWith("HTTP/1.1 200 OK"), page); + assertTrue(page.contains("Cache-Control: no-store")); + assertTrue(page.contains("You can close this tab"), page); + } finally { + l.close(); + } + } + + @Test + public void aRefusalSaysSignInDidNotFinish() throws Exception { + FakeBrowser browser = new FakeBrowser(); + OidcLoopbackRedirect.Listener l = new JavaSEOidcLoopbackRedirect(browser).listen("localhost", 0, "/"); + try { + String uri = l.getRedirectUri(); + assertTrue(uri.startsWith("http://localhost:"), "the redirect keeps the host it was given"); + browser.port = Integer.parseInt(uri.substring("http://localhost:".length(), uri.length() - 1)); + browser.requests = new String[]{get("/?error=access_denied&state=s")}; + assertEquals(uri + "?error=access_denied&state=s", l.await("https://idp.example/auth", 5000)); + browser.finish(); + assertTrue(browser.responses.get(0).contains("Sign-in didn't finish")); + } finally { + l.close(); + } + } + + @Test + public void closingEndsTheWait() throws Exception { + final OidcLoopbackRedirect.Listener l = new JavaSEOidcLoopbackRedirect(new FakeBrowser()) + .listen("127.0.0.1", 0, "/cb"); + new Thread(new Runnable() { + public void run() { + try { + Thread.sleep(300); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } + l.close(); + } + }).start(); + long start = System.currentTimeMillis(); + assertNull(l.await("https://idp.example/auth", 60000)); + assertTrue(System.currentTimeMillis() - start < 10000); + l.close(); + } + + @Test + public void theWaitEndsAtItsTimeout() throws Exception { + OidcLoopbackRedirect.Listener l = new JavaSEOidcLoopbackRedirect(new FakeBrowser()).listen("127.0.0.1", 0, "/cb"); + try { + assertNull(l.await("https://idp.example/auth", 600)); + } finally { + l.close(); + } + } + + @Test + public void aBrowserThatCannotOpenIsAnError() throws Exception { + OidcLoopbackRedirect.Listener l = new JavaSEOidcLoopbackRedirect(new JavaSEOidcLoopbackRedirect.Browser() { + public void open(String url) throws Exception { + throw new IllegalStateException("no browser"); + } + }).listen("127.0.0.1", 0, "/cb"); + try { + l.await("https://idp.example/auth", 5000); + fail("expected an IOException"); + } catch (IOException e) { + assertTrue(e.getMessage().contains("no browser"), e.getMessage()); + } finally { + l.close(); + } + } + + @Test + public void theHeadIsReadUpToItsBlankLineAndNoFurther() throws Exception { + String head = JavaSEOidcLoopbackRedirect.readHead(new ByteArrayInputStream( + "GET /cb HTTP/1.1\r\nHost: x\r\n\r\nBODY".getBytes("ISO-8859-1"))); + assertEquals("GET /cb HTTP/1.1\r\nHost: x\r\n\r\n", head); + assertEquals("GET /cb HTTP/1.1", JavaSEOidcLoopbackRedirect.firstLine(head)); + assertNull(JavaSEOidcLoopbackRedirect.firstLine("GET /cb")); + byte[] huge = new byte[JavaSEOidcLoopbackRedirect.MAX_HEAD * 2]; + java.util.Arrays.fill(huge, (byte) 'a'); + assertEquals(JavaSEOidcLoopbackRedirect.MAX_HEAD, + JavaSEOidcLoopbackRedirect.readHead(new ByteArrayInputStream(huge)).length()); + } +}