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
198 changes: 190 additions & 8 deletions CodenameOne/src/com/codename1/io/oidc/OidcClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -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/<path>` or
/// `http://localhost/<path>`, 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/<path> "
+ "or http://localhost/<path>, 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/<path> "
+ "or http://localhost/<path>, 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;
Expand Down Expand Up @@ -342,12 +409,19 @@ public OidcClient setResponseMode(String mode) {
/// the token set or errors with [OidcException] (e.g. `USER_CANCELLED`,
/// `STATE_MISMATCH`).
public AsyncResource<OidcTokens> authorize() {
if (loopbackRedirectUri != null) {
OidcLoopbackRedirect loopback = SystemBrowser.getLoopbackProvider();
if (loopback != null && loopback.isSupported()) {
requireClient();
return authorizeLoopback(loopback);
}
}
requireConfigured();
final AsyncResource<OidcTokens> out = new AsyncResource<OidcTokens>();
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<String>() {
@Override
Expand All @@ -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<OidcTokens> 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<OidcTokens> {
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.
Expand Down Expand Up @@ -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");
}
Expand All @@ -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));
}
Expand Down Expand Up @@ -949,6 +1118,18 @@ void handleRedirect(String redirectUrl,
String expectedNonce,
PkceChallenge pkce,
final AsyncResource<OidcTokens> 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<OidcTokens> out) {
Map<String, String> 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
Expand Down Expand Up @@ -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<OidcTokens> out) {
Expand All @@ -1007,7 +1189,7 @@ private void exchangeCode(String code,
Map<String, String> args = new HashMap<String, String>();
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);
Expand Down
80 changes: 80 additions & 0 deletions CodenameOne/src/com/codename1/io/oidc/OidcLoopbackRedirect.java
Original file line number Diff line number Diff line change
@@ -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:<port>/<path>` (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();
}
}
Loading
Loading