pre-major refactoring + ext api.
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Marks a handler as requiring a valid JWT. Any bearer token that passes
|
||||
* signature + expiry + issuer validation is accepted — no role check is performed.
|
||||
*
|
||||
* <p>For role-based access use {@link RolesAllowed} instead (it implies authentication).
|
||||
*
|
||||
* <pre>{@code
|
||||
* @Route(method = HttpMethod.GET, path = "/api/profile")
|
||||
* @Authenticated
|
||||
* public class GetProfile extends JacksonHandler { ... }
|
||||
* }</pre>
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface Authenticated {
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Thread-local store for JWT claims, populated by the OIDC middleware before
|
||||
* the handler runs and cleared in the {@code finally} block afterward.
|
||||
*
|
||||
* <p>Safe with virtual threads: each request gets its own virtual thread, so
|
||||
* {@link ThreadLocal} values are naturally isolated per request.
|
||||
*
|
||||
* <pre>{@code
|
||||
* // Inside any handler protected by @Authenticated or @RolesAllowed:
|
||||
*
|
||||
* // Preferred — typed wrapper:
|
||||
* OidcUser user = ClaimsHolder.user();
|
||||
* String email = user.email();
|
||||
* List<String> roles = user.roles("realm_access.roles");
|
||||
*
|
||||
* // Raw escape hatch:
|
||||
* Map<String, Object> all = ClaimsHolder.get();
|
||||
* }</pre>
|
||||
*/
|
||||
public final class ClaimsHolder {
|
||||
|
||||
private static final ThreadLocal<Map<String, Object>> HOLDER = new ThreadLocal<>();
|
||||
|
||||
private ClaimsHolder() {}
|
||||
|
||||
/** Called by the OIDC middleware after successful token validation. */
|
||||
static void set(Map<String, Object> claims) {
|
||||
HOLDER.set(claims);
|
||||
}
|
||||
|
||||
/** Called by the OIDC middleware in the {@code finally} block. */
|
||||
static void clear() {
|
||||
HOLDER.remove();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a type-safe {@link OidcUser} view of the current request's claims,
|
||||
* or {@code null} if the route is not protected by OIDC middleware.
|
||||
*
|
||||
* <p>This is the preferred entry point for both lambda and class-based handlers.
|
||||
*/
|
||||
public static OidcUser user() {
|
||||
Map<String, Object> claims = HOLDER.get();
|
||||
return claims != null ? new OidcUser(claims) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw claims map for the current request, or {@code null} if
|
||||
* the route is not protected by OIDC middleware.
|
||||
*
|
||||
* @see #user() for the preferred type-safe accessor
|
||||
*/
|
||||
public static Map<String, Object> get() {
|
||||
return HOLDER.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of a single claim as a String, or {@code null} if
|
||||
* the claim is absent or the request is not authenticated.
|
||||
*/
|
||||
public static String claim(String key) {
|
||||
Map<String, Object> claims = HOLDER.get();
|
||||
if (claims == null) return null;
|
||||
Object v = claims.get(key);
|
||||
return v != null ? v.toString() : null;
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
/**
|
||||
* OAuth2 client authentication method for the token endpoint (RFC 6749 §2.3).
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link #POST} — credentials sent as {@code client_id} / {@code client_secret}
|
||||
* form fields (default; most providers).</li>
|
||||
* <li>{@link #BASIC} — credentials sent as an {@code Authorization: Basic} header;
|
||||
* body contains only grant-specific parameters.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public enum ClientAuthMethod {
|
||||
/** {@code client_secret_post} — credentials in the request body. */
|
||||
POST,
|
||||
/** {@code client_secret_basic} — credentials in the {@code Authorization} header. */
|
||||
BASIC
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import net.minidev.json.JSONValue;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Fetches and parses the OIDC provider discovery document at
|
||||
* {@code {issuer}/.well-known/openid-configuration}.
|
||||
*/
|
||||
final class DiscoveryClient {
|
||||
|
||||
private DiscoveryClient() {}
|
||||
|
||||
static OidcProviderMetadata fetch(String issuer, HttpClient http) throws Exception {
|
||||
String url = issuer.endsWith("/")
|
||||
? issuer + ".well-known/openid-configuration"
|
||||
: issuer + "/.well-known/openid-configuration";
|
||||
|
||||
HttpResponse<String> resp = http.send(
|
||||
HttpRequest.newBuilder().uri(URI.create(url)).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (resp.statusCode() != 200)
|
||||
throw new IllegalStateException(
|
||||
"OIDC discovery failed [" + resp.statusCode() + "]: " + url);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> doc = (Map<String, Object>) JSONValue.parse(resp.body());
|
||||
|
||||
return new OidcProviderMetadata(
|
||||
require(doc, "authorization_endpoint"),
|
||||
require(doc, "token_endpoint"),
|
||||
(String) doc.get("userinfo_endpoint"), // optional
|
||||
require(doc, "jwks_uri"),
|
||||
(String) doc.get("end_session_endpoint") // optional
|
||||
);
|
||||
}
|
||||
|
||||
private static String require(Map<String, Object> doc, String key) {
|
||||
Object v = doc.get(key);
|
||||
if (v == null) throw new IllegalStateException(
|
||||
"Discovery doc missing required field: " + key);
|
||||
return v.toString();
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Thread-safe in-memory {@link OidcSessionStore}.
|
||||
*
|
||||
* <p>Sessions are lost on restart and not shared across instances. For
|
||||
* production deployments with multiple nodes or restart-persistence requirements,
|
||||
* supply a custom implementation via {@link OidcConfig.Builder#sessionStore}.
|
||||
*/
|
||||
public final class InMemoryOidcSessionStore implements OidcSessionStore {
|
||||
|
||||
private final ConcurrentHashMap<String, OidcSession> store = new ConcurrentHashMap<>();
|
||||
|
||||
@Override public void save(OidcSession s) { store.put(s.id(), s); }
|
||||
@Override public Optional<OidcSession> find(String id) { return Optional.ofNullable(store.get(id)); }
|
||||
@Override public void delete(String id) { store.remove(id); }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import net.minidev.json.JSONValue;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Low-level JWT payload extraction — no signature or expiry validation.
|
||||
*
|
||||
* <p>Use only for tokens received directly from the provider over a trusted TLS
|
||||
* connection (e.g. {@code id_token} from the token endpoint). Bearer tokens on
|
||||
* incoming requests must go through {@link JwtValidator#validate(String)} instead.
|
||||
*/
|
||||
final class JwtUtils {
|
||||
|
||||
private JwtUtils() {}
|
||||
|
||||
/**
|
||||
* Base64URL-decodes the JWT payload and returns the claims as a map.
|
||||
* Signature, expiry, and issuer are NOT checked.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, Object> parseClaims(String jwt) {
|
||||
String[] parts = jwt.split("\\.");
|
||||
if (parts.length < 2) throw new IllegalArgumentException("Malformed JWT: " + jwt);
|
||||
// Pad to a multiple of 4 for the standard decoder
|
||||
String padded = parts[1];
|
||||
switch (padded.length() % 4) {
|
||||
case 2 -> padded += "==";
|
||||
case 3 -> padded += "=";
|
||||
}
|
||||
byte[] payload = Base64.getUrlDecoder().decode(padded);
|
||||
return (Map<String, Object>) JSONValue.parse(
|
||||
new String(payload, StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.jwk.source.JWKSourceBuilder;
|
||||
import com.nimbusds.jose.proc.JWSKeySelector;
|
||||
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import com.nimbusds.jose.util.Resource;
|
||||
import com.nimbusds.jose.util.ResourceRetriever;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
|
||||
import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier;
|
||||
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
|
||||
import dev.relism.exceptions.HttpException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Validates JWTs against a remote JWKS endpoint using Nimbus JOSE+JWT.
|
||||
*
|
||||
* <p>Two validation modes:
|
||||
* <ul>
|
||||
* <li>{@link #validate(String)} — access token bearer validation per request (hot path).
|
||||
* Checks signature, {@code iss}, {@code exp}, {@code iat}, {@code sub}.
|
||||
* Throws {@link HttpException} 401 so the middleware can short-circuit.</li>
|
||||
* <li>{@link #validateIdToken(String, String)} — ID token validation at callback time.
|
||||
* Checks signature, {@code iss}, {@code aud} == clientId, {@code exp}, {@code iat},
|
||||
* {@code sub}, and {@code nonce} (if provided).
|
||||
* Throws {@link OidcValidationException} (not 401 — it is a provider/protocol error).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>JWKS handling: the shared {@link JWKSource} uses caching + rate-limiting + automatic
|
||||
* retry-on-key-miss (key rotation). Both processors share the same source — one JWKS
|
||||
* fetch serves both token types.
|
||||
*/
|
||||
public class JwtValidator {
|
||||
|
||||
private final JWKSource<SecurityContext> jwkSource;
|
||||
private final ConfigurableJWTProcessor<SecurityContext> accessTokenProcessor;
|
||||
private final ConfigurableJWTProcessor<SecurityContext> idTokenProcessor;
|
||||
private final String algorithm;
|
||||
|
||||
/**
|
||||
* @param jwksUri JWKS endpoint URI
|
||||
* @param issuer Expected {@code iss} claim
|
||||
* @param clientId OAuth2 client ID — used as expected {@code aud} in ID tokens
|
||||
* @param algorithm JWS algorithm (e.g. {@code "RS256"})
|
||||
* @param http Shared {@link HttpClient} used for all JWKS fetches — already configured
|
||||
* with the correct TLS policy (trust-all or default trust store).
|
||||
*/
|
||||
public JwtValidator(String jwksUri, String issuer, String clientId,
|
||||
String algorithm, HttpClient http) {
|
||||
try {
|
||||
// Use the caller-supplied HttpClient for JWKS retrieval so that TLS policy
|
||||
// (insecureTls / custom trust store) is applied consistently everywhere.
|
||||
this.jwkSource = JWKSourceBuilder
|
||||
.create(new URL(jwksUri), httpRetriever(http))
|
||||
.cache(true)
|
||||
.rateLimited(true)
|
||||
.retrying(true)
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Failed to init JWKS source: " + jwksUri, e);
|
||||
}
|
||||
this.algorithm = algorithm;
|
||||
this.accessTokenProcessor = buildAccessTokenProcessor(jwkSource, issuer, algorithm);
|
||||
this.idTokenProcessor = buildIdTokenProcessor(jwkSource, issuer, clientId, algorithm);
|
||||
}
|
||||
|
||||
// -- Public API -----------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Validates a JWT access token (bearer on incoming request).
|
||||
* Returns claims on success; throws {@link HttpException} 401 on any failure.
|
||||
*/
|
||||
public Map<String, Object> validate(String token) {
|
||||
if (!isJwt(token)) throw HttpException.unauthorized(); // opaque token — can't validate
|
||||
try {
|
||||
return accessTokenProcessor.process(token, null).getClaims();
|
||||
} catch (Exception e) {
|
||||
throw HttpException.unauthorized();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates an ID token received directly from the token endpoint.
|
||||
*
|
||||
* <p>Checks: signature (JWKS), {@code iss}, {@code aud} == clientId,
|
||||
* {@code exp}, {@code iat}, {@code sub}, and {@code nonce} if provided.
|
||||
*
|
||||
* @param idToken Raw ID token string
|
||||
* @param nonce Nonce sent in the authorization request; {@code null} to skip check
|
||||
* @throws OidcValidationException on any validation failure
|
||||
*/
|
||||
public Map<String, Object> validateIdToken(String idToken, String nonce) {
|
||||
try {
|
||||
Map<String, Object> claims = idTokenProcessor.process(idToken, null).getClaims();
|
||||
if (nonce != null && !nonce.equals(claims.get("nonce")))
|
||||
throw new OidcValidationException("ID token nonce mismatch", null);
|
||||
return claims;
|
||||
} catch (OidcValidationException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new OidcValidationException("ID token validation failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} if {@code token} is a signed JWT (three dot-separated Base64URL parts).
|
||||
* Used to detect opaque access tokens before attempting JWKS validation.
|
||||
*/
|
||||
public static boolean isJwt(String token) {
|
||||
if (token == null || token.isBlank()) return false;
|
||||
int dots = 0;
|
||||
for (int i = 0; i < token.length(); i++) if (token.charAt(i) == '.') dots++;
|
||||
return dots == 2;
|
||||
}
|
||||
|
||||
// -- Processors -----------------------------------------------------------
|
||||
|
||||
private static ConfigurableJWTProcessor<SecurityContext> buildAccessTokenProcessor(
|
||||
JWKSource<SecurityContext> src, String issuer, String algorithm) {
|
||||
|
||||
ConfigurableJWTProcessor<SecurityContext> p = new DefaultJWTProcessor<>();
|
||||
p.setJWSKeySelector(keySelector(src, algorithm));
|
||||
// iss required; aud not enforced on ATs (varies by provider)
|
||||
if (issuer != null && !issuer.isBlank()) {
|
||||
p.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier<>(
|
||||
new JWTClaimsSet.Builder().issuer(issuer).build(),
|
||||
Set.of("sub", "iat", "exp")));
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
private static ConfigurableJWTProcessor<SecurityContext> buildIdTokenProcessor(
|
||||
JWKSource<SecurityContext> src, String issuer, String clientId, String algorithm) {
|
||||
|
||||
ConfigurableJWTProcessor<SecurityContext> p = new DefaultJWTProcessor<>();
|
||||
p.setJWSKeySelector(keySelector(src, algorithm));
|
||||
// iss + aud = clientId strictly required (OIDC Core §3.1.3.7)
|
||||
JWTClaimsSet.Builder required = new JWTClaimsSet.Builder();
|
||||
if (issuer != null) required.issuer(issuer);
|
||||
if (clientId != null) required.audience(clientId);
|
||||
p.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier<>(
|
||||
required.build(), Set.of("sub", "iat", "exp")));
|
||||
return p;
|
||||
}
|
||||
|
||||
private static JWSKeySelector<SecurityContext> keySelector(
|
||||
JWKSource<SecurityContext> src, String algorithm) {
|
||||
return new JWSVerificationKeySelector<>(JWSAlgorithm.parse(algorithm), src);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a {@link HttpClient} as a Nimbus {@link ResourceRetriever}.
|
||||
* The client already carries the correct TLS policy (trust-all or default),
|
||||
* so JWKS fetches honour the same SSL configuration as discovery and token requests.
|
||||
*/
|
||||
private static ResourceRetriever httpRetriever(HttpClient http) {
|
||||
return url -> {
|
||||
try {
|
||||
HttpResponse<String> resp = http.send(
|
||||
HttpRequest.newBuilder().uri(url.toURI()).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
if (resp.statusCode() != 200)
|
||||
throw new IOException("JWKS fetch failed [" + resp.statusCode() + "]: " + url);
|
||||
String contentType = resp.headers()
|
||||
.firstValue("Content-Type").orElse("application/json");
|
||||
return new Resource(resp.body(), contentType);
|
||||
} catch (IOException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new IOException("JWKS retrieval error: " + e.getMessage(), e);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
/**
|
||||
* Full OIDC client configuration. Build via
|
||||
* {@link #builder(String, String, String, String)} or {@link #fromEnv()}.
|
||||
*
|
||||
* <p>Required fields: {@code issuer}, {@code clientId}, {@code clientSecret},
|
||||
* {@code redirectUri}. Everything else has a sensible default.
|
||||
*
|
||||
* <p>If {@code redirectUri} starts with {@code /} it is treated as server-relative:
|
||||
* the absolute URL is resolved at request time using {@link #selfScheme()} and the
|
||||
* incoming {@code Host} header. Use {@link Builder#https()} when behind TLS.
|
||||
*
|
||||
* <pre>{@code
|
||||
* // Keycloak
|
||||
* OidcConfig.builder(
|
||||
* "https://keycloak.example.com/realms/myrealm",
|
||||
* "my-app", "secret", "/auth/callback")
|
||||
* .rolesClaimPath("realm_access.roles") // Keycloak default
|
||||
* .build();
|
||||
*
|
||||
* // Authelia
|
||||
* OidcConfig.builder(
|
||||
* "https://auth.example.com",
|
||||
* "my-app", "secret", "/auth/callback")
|
||||
* .rolesClaimPath("groups")
|
||||
* .build();
|
||||
*
|
||||
* // Two tenants on one server
|
||||
* OidcConfig tenantA = OidcConfig.builder("https://idp/realms/a", ..., "/tenantA/auth/callback")
|
||||
* .routePrefix("/tenantA/auth").build();
|
||||
* OidcConfig tenantB = OidcConfig.builder("https://idp/realms/b", ..., "/tenantB/auth/callback")
|
||||
* .routePrefix("/tenantB/auth").build();
|
||||
* app.install(new OidcExtension(tenantA))
|
||||
* .install(new OidcExtension(tenantB));
|
||||
* }</pre>
|
||||
*/
|
||||
public final class OidcConfig {
|
||||
|
||||
private final String issuer;
|
||||
private final String clientId;
|
||||
private final String clientSecret;
|
||||
private final String redirectUri;
|
||||
private final String scopes;
|
||||
private final String routePrefix;
|
||||
private final String selfScheme;
|
||||
private final String rolesClaimPath;
|
||||
private final String algorithm;
|
||||
private final String postLogoutRedirectUri;
|
||||
private final OidcSessionStore sessionStore;
|
||||
private final boolean insecureTls;
|
||||
private final ClientAuthMethod clientAuthMethod;
|
||||
private final String schemeName;
|
||||
|
||||
private OidcConfig(Builder b) {
|
||||
this.issuer = require(b.issuer, "issuer");
|
||||
this.clientId = require(b.clientId, "clientId");
|
||||
this.clientSecret = require(b.clientSecret, "clientSecret");
|
||||
this.redirectUri = require(b.redirectUri, "redirectUri");
|
||||
this.scopes = b.scopes;
|
||||
this.routePrefix = b.routePrefix;
|
||||
this.selfScheme = b.selfScheme;
|
||||
this.rolesClaimPath = b.rolesClaimPath;
|
||||
this.algorithm = b.algorithm;
|
||||
this.postLogoutRedirectUri = b.postLogoutRedirectUri;
|
||||
this.sessionStore = b.sessionStore != null ? b.sessionStore
|
||||
: new InMemoryOidcSessionStore();
|
||||
this.insecureTls = b.insecureTls;
|
||||
this.clientAuthMethod = b.clientAuthMethod;
|
||||
this.schemeName = b.schemeName != null ? b.schemeName : deriveScheme(this.issuer);
|
||||
}
|
||||
|
||||
// -- Getters --------------------------------------------------------------
|
||||
|
||||
public String issuer() { return issuer; }
|
||||
public String clientId() { return clientId; }
|
||||
public String clientSecret() { return clientSecret; }
|
||||
public String redirectUri() { return redirectUri; }
|
||||
public String scopes() { return scopes; }
|
||||
public String routePrefix() { return routePrefix; }
|
||||
public String selfScheme() { return selfScheme; }
|
||||
public String rolesClaimPath() { return rolesClaimPath; }
|
||||
public String algorithm() { return algorithm; }
|
||||
public String postLogoutRedirectUri() { return postLogoutRedirectUri; }
|
||||
public OidcSessionStore sessionStore() { return sessionStore; }
|
||||
/** If {@code true}, TLS certificate validation is skipped. <b>Never use in production.</b> */
|
||||
public boolean insecureTls() { return insecureTls; }
|
||||
public ClientAuthMethod clientAuthMethod() { return clientAuthMethod; }
|
||||
/** OpenAPI security scheme name (derived from issuer if not set explicitly). */
|
||||
public String schemeName() { return schemeName; }
|
||||
|
||||
// -- Factory --------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Reads configuration from environment variables:
|
||||
* <pre>
|
||||
* OIDC_ISSUER required
|
||||
* OIDC_CLIENT_ID required
|
||||
* OIDC_CLIENT_SECRET required
|
||||
* OIDC_REDIRECT_URI required (e.g. /auth/callback)
|
||||
* OIDC_SCOPES default: openid profile email
|
||||
* OIDC_ROUTE_PREFIX default: /auth
|
||||
* OIDC_SELF_SCHEME default: http
|
||||
* OIDC_ROLES_CLAIM default: realm_access.roles
|
||||
* OIDC_ALGORITHM default: RS256
|
||||
* OIDC_POST_LOGOUT_REDIRECT default: /
|
||||
* </pre>
|
||||
*/
|
||||
public static OidcConfig fromEnv() {
|
||||
return builder(env("OIDC_ISSUER"), env("OIDC_CLIENT_ID"),
|
||||
env("OIDC_CLIENT_SECRET"), env("OIDC_REDIRECT_URI"))
|
||||
.scopes (envOr("OIDC_SCOPES", "openid profile email"))
|
||||
.routePrefix (envOr("OIDC_ROUTE_PREFIX", "/auth"))
|
||||
.selfScheme (envOr("OIDC_SELF_SCHEME", "http"))
|
||||
.rolesClaimPath (envOr("OIDC_ROLES_CLAIM", "realm_access.roles"))
|
||||
.algorithm (envOr("OIDC_ALGORITHM", "RS256"))
|
||||
.postLogoutRedirectUri(envOr("OIDC_POST_LOGOUT_REDIRECT", "/"))
|
||||
.clientAuthMethod(ClientAuthMethod.valueOf(
|
||||
envOr("OIDC_CLIENT_AUTH_METHOD", "POST").toUpperCase()))
|
||||
.build();
|
||||
}
|
||||
|
||||
public static Builder builder(String issuer, String clientId,
|
||||
String clientSecret, String redirectUri) {
|
||||
return new Builder(issuer, clientId, clientSecret, redirectUri);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience factory for Keycloak: constructs the issuer as
|
||||
* {@code {serverUrl}/realms/{realm}} automatically.
|
||||
*
|
||||
* <pre>{@code
|
||||
* OidcConfig.keycloak(
|
||||
* "https://keycloak.example.com", "flashboard",
|
||||
* "my-app", "secret", "/auth/callback")
|
||||
* .https()
|
||||
* .build();
|
||||
* }</pre>
|
||||
*/
|
||||
public static Builder keycloak(String serverUrl, String realm,
|
||||
String clientId, String clientSecret,
|
||||
String redirectUri) {
|
||||
String base = serverUrl.endsWith("/") ? serverUrl.substring(0, serverUrl.length() - 1) : serverUrl;
|
||||
String issuer = base + "/realms/" + realm;
|
||||
return new Builder(issuer, clientId, clientSecret, redirectUri)
|
||||
.rolesClaimPath("realm_access.roles"); // Keycloak default
|
||||
}
|
||||
|
||||
// -- Helpers --------------------------------------------------------------
|
||||
|
||||
private static String require(String v, String name) {
|
||||
if (v == null || v.isBlank())
|
||||
throw new IllegalArgumentException("OidcConfig: " + name + " is required");
|
||||
return v;
|
||||
}
|
||||
|
||||
private static String env(String key) {
|
||||
String v = System.getenv(key);
|
||||
if (v == null || v.isBlank())
|
||||
throw new IllegalArgumentException("Missing required env var: " + key);
|
||||
return v;
|
||||
}
|
||||
|
||||
private static String envOr(String key, String def) {
|
||||
String v = System.getenv(key);
|
||||
return (v != null && !v.isBlank()) ? v : def;
|
||||
}
|
||||
|
||||
// -- Builder --------------------------------------------------------------
|
||||
|
||||
public static final class Builder {
|
||||
|
||||
private final String issuer;
|
||||
private final String clientId;
|
||||
private final String clientSecret;
|
||||
private final String redirectUri;
|
||||
|
||||
private String scopes = "openid profile email";
|
||||
private String routePrefix = "/auth";
|
||||
private String selfScheme = "http";
|
||||
private String rolesClaimPath = "realm_access.roles";
|
||||
private String algorithm = "RS256";
|
||||
private String postLogoutRedirectUri = "/";
|
||||
private OidcSessionStore sessionStore;
|
||||
private boolean insecureTls = false;
|
||||
private ClientAuthMethod clientAuthMethod = ClientAuthMethod.POST;
|
||||
private String schemeName = null;
|
||||
|
||||
private Builder(String issuer, String clientId, String clientSecret, String redirectUri) {
|
||||
this.issuer = issuer;
|
||||
this.clientId = clientId;
|
||||
this.clientSecret = clientSecret;
|
||||
this.redirectUri = redirectUri;
|
||||
}
|
||||
|
||||
/** Override requested scopes (default: {@code openid profile email}). */
|
||||
public Builder scopes(String scopes) { this.scopes = scopes; return this; }
|
||||
/** Route prefix for login/callback/logout (default: {@code /auth}). */
|
||||
public Builder routePrefix(String prefix) { this.routePrefix = prefix; return this; }
|
||||
/** Scheme used when resolving self-relative redirect URIs (default: {@code http}). */
|
||||
public Builder selfScheme(String scheme) { this.selfScheme = scheme; return this; }
|
||||
/** Shorthand for {@code selfScheme("https")}. */
|
||||
public Builder https() { return selfScheme("https"); }
|
||||
/** Dot-separated path to the roles array in JWT claims (default: {@code realm_access.roles}). */
|
||||
public Builder rolesClaimPath(String path) { this.rolesClaimPath = path; return this; }
|
||||
/** JWS algorithm (default: {@code RS256}). */
|
||||
public Builder algorithm(String algorithm) { this.algorithm = algorithm; return this; }
|
||||
/** Where to redirect after logout (default: {@code /}). */
|
||||
public Builder postLogoutRedirectUri(String uri) { this.postLogoutRedirectUri = uri; return this; }
|
||||
/** Custom session store (default: {@link InMemoryOidcSessionStore}). */
|
||||
public Builder sessionStore(OidcSessionStore store) { this.sessionStore = store; return this; }
|
||||
/**
|
||||
* Disables TLS certificate verification for all HTTP calls made by this extension.
|
||||
* <b>Only use in development with self-signed certificates — never in production.</b>
|
||||
*/
|
||||
public Builder insecureTls() { this.insecureTls = true; return this; }
|
||||
/** Token endpoint client authentication method (default: {@link ClientAuthMethod#POST}). */
|
||||
public Builder clientAuthMethod(ClientAuthMethod method) { this.clientAuthMethod = method; return this; }
|
||||
/** Override the OpenAPI security scheme name (default: derived from the issuer URI). */
|
||||
public Builder schemeName(String name) { this.schemeName = name; return this; }
|
||||
|
||||
public OidcConfig build() { return new OidcConfig(this); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives a short, human-readable scheme name from the issuer URI.
|
||||
* Takes the last non-empty path segment; falls back to the host.
|
||||
*
|
||||
* <p>Examples:
|
||||
* <ul>
|
||||
* <li>{@code https://keycloak.dev.home/realms/flashboard} → {@code "flashboard"}</li>
|
||||
* <li>{@code https://auth.example.com} → {@code "auth.example.com"}</li>
|
||||
* </ul>
|
||||
*/
|
||||
private static String deriveScheme(String issuer) {
|
||||
try {
|
||||
java.net.URI uri = new java.net.URI(issuer);
|
||||
String path = uri.getPath();
|
||||
if (path != null && !path.isEmpty()) {
|
||||
String[] parts = path.split("/");
|
||||
for (int i = parts.length - 1; i >= 0; i--) {
|
||||
if (!parts[i].isEmpty()) return parts[i];
|
||||
}
|
||||
}
|
||||
return uri.getHost();
|
||||
} catch (Exception e) {
|
||||
return "oidc";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import dev.relism.extension.ExtensionContext;
|
||||
import dev.relism.extension.FlashApp;
|
||||
import dev.relism.extension.FlashExtension;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Full OIDC Authorization Code + PKCE flow for Flash.
|
||||
*
|
||||
* <p>On {@link #install}, the extension:
|
||||
* <ol>
|
||||
* <li>Fetches the provider discovery document — fail-fast at startup.</li>
|
||||
* <li>Registers three routes on the {@link FlashApp}:
|
||||
* <ul>
|
||||
* <li>{@code GET {prefix}/login} — builds the authorization URL and redirects.</li>
|
||||
* <li>{@code GET {prefix}/callback} — exchanges the code, creates a session, redirects.</li>
|
||||
* <li>{@code POST {prefix}/logout} — invalidates the session, redirects to the provider's
|
||||
* end-session endpoint (if available) or to {@link OidcConfig#postLogoutRedirectUri()}.</li>
|
||||
* </ul>
|
||||
* </li>
|
||||
* <li>Provides {@link OidcMiddleware} and {@link JwtValidator} in the context.</li>
|
||||
* <li>Registers an annotation processor for {@link Authenticated} and {@link RolesAllowed}.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <pre>{@code
|
||||
* // Keycloak
|
||||
* app.install(new OidcExtension(
|
||||
* OidcConfig.builder(
|
||||
* "https://keycloak.example.com/realms/myrealm",
|
||||
* "my-app", "secret", "/auth/callback")
|
||||
* .rolesClaimPath("realm_access.roles")
|
||||
* .build()));
|
||||
*
|
||||
* // Two providers / tenants on one server
|
||||
* app.install(new OidcExtension(tenantAConfig))
|
||||
* .install(new OidcExtension(tenantBConfig));
|
||||
* }</pre>
|
||||
*/
|
||||
public class OidcExtension implements FlashExtension {
|
||||
|
||||
private final OidcConfig config;
|
||||
|
||||
public OidcExtension(OidcConfig config) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void install(FlashApp app, ExtensionContext ctx) {
|
||||
|
||||
// 1. Build the shared HttpClient (optionally with TLS verification disabled)
|
||||
HttpClient http = buildHttpClient(config);
|
||||
|
||||
// 2. Discover provider endpoints (blocking; fail fast at startup)
|
||||
OidcProviderMetadata meta;
|
||||
try {
|
||||
meta = DiscoveryClient.fetch(config.issuer(), http);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException(
|
||||
"OIDC discovery failed for issuer: " + config.issuer(), e);
|
||||
}
|
||||
|
||||
// 3. JWKS-backed access-token validator
|
||||
JwtValidator validator = new JwtValidator(
|
||||
meta.jwksUri(), config.issuer(), config.clientId(),
|
||||
config.algorithm(), http);
|
||||
|
||||
// 4. PKCE state store (per extension instance — safe for multi-tenant)
|
||||
OidcStateStore stateStore = new OidcStateStore();
|
||||
|
||||
// 5. Shared token client (injected into middleware for refresh)
|
||||
TokenClient tokenClient = new TokenClient(http, config);
|
||||
|
||||
// 6. Middleware (also exposed in context for manual lambda-route protection)
|
||||
OidcMiddleware oidcMw = new OidcMiddleware(validator, config, meta, tokenClient);
|
||||
ctx.provide(OidcMiddleware.class, oidcMw);
|
||||
ctx.provide(JwtValidator.class, validator);
|
||||
|
||||
String prefix = config.routePrefix();
|
||||
|
||||
// ── GET {prefix}/login ────────────────────────────────────────────────
|
||||
// Builds the provider authorization URL with PKCE + state and redirects.
|
||||
// Optional query param: ?redirect={relative-url} (default: /)
|
||||
app.get(prefix + "/login", (req, res) -> {
|
||||
String verifier = PkceUtils.generateVerifier();
|
||||
String challenge = PkceUtils.computeChallenge(verifier);
|
||||
String state = UUID.randomUUID().toString(); // CSRF protection
|
||||
String nonce = UUID.randomUUID().toString(); // ID token replay protection
|
||||
|
||||
String redirect = req.query("redirect");
|
||||
// Only allow relative paths — prevents open-redirect attacks
|
||||
if (redirect == null || !redirect.startsWith("/")) redirect = "/";
|
||||
|
||||
stateStore.put(state, redirect, verifier, nonce);
|
||||
|
||||
String authUrl = meta.authorizationEndpoint()
|
||||
+ "?response_type=code"
|
||||
+ "&client_id=" + enc(config.clientId())
|
||||
+ "&redirect_uri=" + enc(absoluteRedirectUri(req))
|
||||
+ "&scope=" + enc(config.scopes())
|
||||
+ "&state=" + state
|
||||
+ "&nonce=" + enc(nonce)
|
||||
+ "&code_challenge=" + challenge
|
||||
+ "&code_challenge_method=S256";
|
||||
|
||||
res.status(302).header("Location", authUrl);
|
||||
return null;
|
||||
}).with();
|
||||
|
||||
// ── GET {prefix}/callback ─────────────────────────────────────────────
|
||||
// Validates state, exchanges code for tokens, creates session, redirects.
|
||||
app.get(prefix + "/callback", (req, res) -> {
|
||||
String error = req.query("error");
|
||||
if (error != null) {
|
||||
res.status(400);
|
||||
return "Authentication error: " + error
|
||||
+ (req.query("error_description") != null
|
||||
? " — " + req.query("error_description") : "");
|
||||
}
|
||||
|
||||
String code = req.query("code");
|
||||
String state = req.query("state");
|
||||
|
||||
OidcStateStore.Entry entry = stateStore.consumeAndRemove(state).orElse(null);
|
||||
if (entry == null) {
|
||||
res.status(400);
|
||||
return "Invalid or expired state parameter";
|
||||
}
|
||||
|
||||
OidcTokenResponse tokens = tokenClient.exchangeCode(
|
||||
meta.tokenEndpoint(), code, absoluteRedirectUri(req), entry.codeVerifier());
|
||||
|
||||
// Validate ID token: signature + iss + aud + exp + iat + sub + nonce (OIDC Core §3.1.3.7)
|
||||
if (tokens.idToken() != null) {
|
||||
try {
|
||||
validator.validateIdToken(tokens.idToken(), entry.nonce());
|
||||
} catch (OidcValidationException e) {
|
||||
res.status(400);
|
||||
return "ID token validation failed: " + e.getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object> claims = mergeClaims(tokens);
|
||||
|
||||
OidcSession session = new OidcSession(
|
||||
UUID.randomUUID().toString(),
|
||||
tokens.accessToken(),
|
||||
tokens.idToken(),
|
||||
tokens.refreshToken(),
|
||||
Instant.now().plusSeconds(tokens.expiresIn()),
|
||||
claims
|
||||
);
|
||||
config.sessionStore().save(session);
|
||||
|
||||
res.status(302)
|
||||
.header("Set-Cookie", sessionCookie(session.id()))
|
||||
.header("Location", entry.originalUrl());
|
||||
return null;
|
||||
}).with();
|
||||
|
||||
// ── POST {prefix}/logout ──────────────────────────────────────────────
|
||||
// Invalidates the local session and redirects to the provider's
|
||||
// end_session_endpoint (with id_token_hint) if available.
|
||||
app.post(prefix + "/logout", (req, res) -> {
|
||||
String sessionId = OidcMiddleware.cookieValue(req, "oidc_session");
|
||||
String idTokenHint = null;
|
||||
|
||||
if (sessionId != null) {
|
||||
config.sessionStore().find(sessionId)
|
||||
.ifPresent(s -> {}); // capture id_token before delete
|
||||
OidcSession session = config.sessionStore().find(sessionId).orElse(null);
|
||||
if (session != null) idTokenHint = session.idToken();
|
||||
config.sessionStore().delete(sessionId);
|
||||
}
|
||||
|
||||
String clearCookie = "oidc_session=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax";
|
||||
String location;
|
||||
|
||||
if (meta.endSessionEndpoint() != null) {
|
||||
String postLogout = absoluteSelf(req, config.postLogoutRedirectUri());
|
||||
StringBuilder url = new StringBuilder(meta.endSessionEndpoint())
|
||||
.append("?post_logout_redirect_uri=").append(enc(postLogout));
|
||||
if (idTokenHint != null)
|
||||
url.append("&id_token_hint=").append(enc(idTokenHint));
|
||||
location = url.toString();
|
||||
} else {
|
||||
location = config.postLogoutRedirectUri();
|
||||
}
|
||||
|
||||
res.status(302)
|
||||
.header("Set-Cookie", clearCookie)
|
||||
.header("Location", location);
|
||||
return null;
|
||||
}).with();
|
||||
|
||||
// 5. Annotation processor for @Authenticated / @RolesAllowed
|
||||
ctx.addAnnotationProcessor(handlerClass -> {
|
||||
RolesAllowed roles = handlerClass.getAnnotation(RolesAllowed.class);
|
||||
if (roles != null) return List.of(oidcMw.rolesMiddleware(roles.value()));
|
||||
|
||||
Authenticated auth = handlerClass.getAnnotation(Authenticated.class);
|
||||
if (auth != null) return List.of(oidcMw.authenticatedMiddleware());
|
||||
|
||||
return List.of();
|
||||
});
|
||||
|
||||
// Register OpenAPI security scheme if flash-ext-openapi is on the classpath
|
||||
try {
|
||||
OpenApiIntegration.register(ctx, config, meta);
|
||||
} catch (NoClassDefFoundError ignored) {
|
||||
// flash-ext-openapi not available — OpenAPI integration disabled
|
||||
}
|
||||
}
|
||||
|
||||
// -- Helpers --------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Merges claims from both the access token and the ID token.
|
||||
* The access token carries provider-specific data like {@code realm_access.roles};
|
||||
* the ID token carries standard identity claims (sub, email, name, …).
|
||||
* ID token values win on conflict so that verified identity claims are authoritative.
|
||||
*/
|
||||
private static Map<String, Object> mergeClaims(OidcTokenResponse tokens) {
|
||||
Map<String, Object> merged = new HashMap<>();
|
||||
// Access token first — provides roles, resource_access, etc.
|
||||
if (tokens.accessToken() != null) {
|
||||
merged.putAll(JwtUtils.parseClaims(tokens.accessToken()));
|
||||
}
|
||||
// ID token overrides — its identity claims (sub, email, name, …) take priority.
|
||||
if (tokens.idToken() != null) {
|
||||
merged.putAll(JwtUtils.parseClaims(tokens.idToken()));
|
||||
}
|
||||
return Map.copyOf(merged);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an {@link HttpClient}. If {@link OidcConfig#insecureTls()} is set,
|
||||
* installs a trust-all {@link SSLContext} that accepts any certificate.
|
||||
* <b>Only safe for development with self-signed certificates.</b>
|
||||
*/
|
||||
private static HttpClient buildHttpClient(OidcConfig config) {
|
||||
if (!config.insecureTls()) return HttpClient.newHttpClient();
|
||||
try {
|
||||
TrustManager[] trustAll = { new X509TrustManager() {
|
||||
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
|
||||
public void checkClientTrusted(X509Certificate[] c, String a) {}
|
||||
public void checkServerTrusted(X509Certificate[] c, String a) {}
|
||||
}};
|
||||
SSLContext ctx = SSLContext.getInstance("TLS");
|
||||
ctx.init(null, trustAll, new SecureRandom());
|
||||
return HttpClient.newBuilder().sslContext(ctx).build();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Failed to create trust-all SSLContext", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the configured {@code redirectUri}. If it starts with {@code /},
|
||||
* prepends {@code selfScheme://Host} from the current request.
|
||||
*/
|
||||
private String absoluteRedirectUri(dev.relism.models.Request req) {
|
||||
return absoluteSelf(req, config.redirectUri());
|
||||
}
|
||||
|
||||
private String absoluteSelf(dev.relism.models.Request req, String uri) {
|
||||
if (!uri.startsWith("/")) return uri;
|
||||
return config.selfScheme() + "://" + req.header("Host") + uri;
|
||||
}
|
||||
|
||||
private static String enc(String v) {
|
||||
return URLEncoder.encode(v, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String sessionCookie(String id) {
|
||||
return "oidc_session=" + id + "; HttpOnly; Path=/; SameSite=Lax";
|
||||
}
|
||||
|
||||
/**
|
||||
* Loaded lazily so that {@code flash-ext-openapi} classes are only resolved at
|
||||
* runtime when {@link dev.relism.ext.openapi.OpenApiSecurityRegistry} is actually on the classpath.
|
||||
* If not present, the {@link NoClassDefFoundError} is caught at the call site.
|
||||
*/
|
||||
private static final class OpenApiIntegration {
|
||||
static void register(dev.relism.extension.ExtensionContext ctx,
|
||||
OidcConfig config, OidcProviderMetadata meta) {
|
||||
ctx.find(dev.relism.ext.openapi.OpenApiSecurityRegistry.class)
|
||||
.ifPresent(registry -> registry.add(new dev.relism.ext.openapi.OpenApiSecurityContributor() {
|
||||
|
||||
@Override
|
||||
public String schemeName() { return config.schemeName(); }
|
||||
|
||||
@Override
|
||||
public java.util.Map<String, Object> schemeDefinition() {
|
||||
// Declare only the authorizationCode flow so Swagger UI shows
|
||||
// a single clean "Authorize" dialog instead of expanding every
|
||||
// grant type from the discovery document.
|
||||
java.util.Map<String, String> scopesMap = new java.util.LinkedHashMap<>();
|
||||
for (String s : config.scopes().split("\\s+")) {
|
||||
if (!s.isBlank()) scopesMap.put(s, s);
|
||||
}
|
||||
java.util.Map<String, Object> flow = new java.util.LinkedHashMap<>();
|
||||
flow.put("authorizationUrl", meta.authorizationEndpoint());
|
||||
flow.put("tokenUrl", meta.tokenEndpoint());
|
||||
flow.put("scopes", scopesMap);
|
||||
|
||||
java.util.Map<String, Object> scheme = new java.util.LinkedHashMap<>();
|
||||
scheme.put("type", "oauth2");
|
||||
scheme.put("flows", java.util.Map.of("authorizationCode", flow));
|
||||
return scheme;
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.List<String> requiredFor(Class<?> handlerClass) {
|
||||
dev.relism.ext.oidc.RolesAllowed roles =
|
||||
handlerClass.getAnnotation(dev.relism.ext.oidc.RolesAllowed.class);
|
||||
if (roles != null) return java.util.Arrays.asList(roles.value());
|
||||
|
||||
dev.relism.ext.oidc.Authenticated auth =
|
||||
handlerClass.getAnnotation(dev.relism.ext.oidc.Authenticated.class);
|
||||
if (auth != null) return java.util.List.of();
|
||||
|
||||
return null; // not secured by this contributor
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import dev.relism.exceptions.HttpException;
|
||||
import dev.relism.models.Request;
|
||||
import dev.relism.routing.Middleware;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Request-level OIDC middleware. Exposed in the {@link dev.relism.extension.ExtensionContext}
|
||||
* for manual use on lambda routes; injected automatically for handlers annotated with
|
||||
* {@link Authenticated} or {@link RolesAllowed}.
|
||||
*
|
||||
* <p>Resolution order on each request:
|
||||
* <ol>
|
||||
* <li>{@code Authorization: Bearer ...} header — validated via JWKS ({@link JwtValidator}).</li>
|
||||
* <li>{@code oidc_session} cookie — looked up in {@link OidcSessionStore}; transparently
|
||||
* refreshed if the access token is expired.</li>
|
||||
* <li>Browser clients (no {@code Accept: application/json}) → redirect to
|
||||
* {@code {routePrefix}/login?redirect={path}}.</li>
|
||||
* <li>API clients → 401.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <pre>{@code
|
||||
* // Manual use on a lambda route:
|
||||
* OidcMiddleware oidc = app.ctx().require(OidcMiddleware.class);
|
||||
* app.get("/api/me", (req, res) -> ClaimsHolder.claim("sub"), oidc.protect());
|
||||
* app.delete("/admin/users/{id}", handler, oidc.requireRole("admin"));
|
||||
* }</pre>
|
||||
*/
|
||||
public class OidcMiddleware {
|
||||
|
||||
private final JwtValidator validator;
|
||||
private final OidcConfig config;
|
||||
private final OidcProviderMetadata meta;
|
||||
private final TokenClient tokenClient;
|
||||
|
||||
OidcMiddleware(JwtValidator validator, OidcConfig config,
|
||||
OidcProviderMetadata meta, TokenClient tokenClient) {
|
||||
this.validator = validator;
|
||||
this.config = config;
|
||||
this.meta = meta;
|
||||
this.tokenClient = tokenClient;
|
||||
}
|
||||
|
||||
// -- Public API -----------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Validates the bearer token or session cookie. Browser clients are redirected
|
||||
* to the login page on failure; API clients receive 401.
|
||||
*/
|
||||
public Middleware protect() {
|
||||
return next -> (req, res) -> {
|
||||
Map<String, Object> claims = resolve(req, res);
|
||||
if (claims == null) return null; // redirect already written
|
||||
ClaimsHolder.set(claims);
|
||||
try {
|
||||
return next.handle(req, res);
|
||||
} finally {
|
||||
ClaimsHolder.clear();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link #protect()} but also enforces that the caller holds at least one
|
||||
* of the given roles (OR semantics). Roles are extracted via
|
||||
* {@link OidcConfig#rolesClaimPath()}.
|
||||
*/
|
||||
public Middleware requireRole(String... roles) {
|
||||
return next -> (req, res) -> {
|
||||
Map<String, Object> claims = resolve(req, res);
|
||||
if (claims == null) return null;
|
||||
checkRoles(claims, roles);
|
||||
ClaimsHolder.set(claims);
|
||||
try {
|
||||
return next.handle(req, res);
|
||||
} finally {
|
||||
ClaimsHolder.clear();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// -- Package-private: AnnotationProcessor hooks ---------------------------
|
||||
|
||||
Middleware authenticatedMiddleware() { return protect(); }
|
||||
Middleware rolesMiddleware(String[] required) { return requireRole(required); }
|
||||
|
||||
// -- Internals ------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns claims on success, or {@code null} if a redirect was already written to
|
||||
* {@code res}. Throws {@link HttpException} 401/403 for API clients.
|
||||
*/
|
||||
private Map<String, Object> resolve(Request req, dev.relism.models.Response res) {
|
||||
// 1. Bearer token
|
||||
String auth = req.header("Authorization");
|
||||
if (auth != null && auth.startsWith("Bearer "))
|
||||
return validator.validate(auth.substring(7));
|
||||
|
||||
// 2. Session cookie
|
||||
String sessionId = cookieValue(req, "oidc_session");
|
||||
if (sessionId != null) {
|
||||
Optional<OidcSession> found = config.sessionStore().find(sessionId);
|
||||
if (found.isPresent()) {
|
||||
OidcSession session = found.get();
|
||||
|
||||
if (!session.isAccessTokenExpired())
|
||||
return session.claims();
|
||||
|
||||
// Access token expired — try silent refresh
|
||||
if (session.refreshToken() != null) {
|
||||
try {
|
||||
OidcSession refreshed = doRefresh(session);
|
||||
config.sessionStore().save(refreshed);
|
||||
return refreshed.claims();
|
||||
} catch (Exception ignored) {
|
||||
// Refresh failed — fall through to re-authenticate
|
||||
}
|
||||
}
|
||||
config.sessionStore().delete(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. No valid credentials
|
||||
String accept = req.header("Accept");
|
||||
if (accept != null && accept.contains("application/json"))
|
||||
throw HttpException.unauthorized();
|
||||
|
||||
// Browser — redirect to login, preserving the original URL in state
|
||||
String loginUrl = config.routePrefix() + "/login?redirect="
|
||||
+ URLEncoder.encode(req.path(), StandardCharsets.UTF_8);
|
||||
res.status(302).header("Location", loginUrl);
|
||||
return null;
|
||||
}
|
||||
|
||||
private OidcSession doRefresh(OidcSession old) throws Exception {
|
||||
OidcTokenResponse tokens = tokenClient.refresh(
|
||||
meta.tokenEndpoint(), old.refreshToken());
|
||||
|
||||
Map<String, Object> claims = mergeRefreshedClaims(tokens, old);
|
||||
|
||||
return new OidcSession(
|
||||
old.id(),
|
||||
tokens.accessToken(),
|
||||
tokens.idToken() != null ? tokens.idToken() : old.idToken(),
|
||||
tokens.refreshToken() != null ? tokens.refreshToken() : old.refreshToken(),
|
||||
Instant.now().plusSeconds(tokens.expiresIn()),
|
||||
claims
|
||||
);
|
||||
}
|
||||
|
||||
private void checkRoles(Map<String, Object> claims, String[] required) {
|
||||
List<String> actual = extractRoles(claims);
|
||||
for (String role : required) {
|
||||
if (actual.contains(role)) return;
|
||||
}
|
||||
throw HttpException.forbidden();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<String> extractRoles(Map<String, Object> claims) {
|
||||
String[] parts = config.rolesClaimPath().split("\\.");
|
||||
Object current = claims;
|
||||
for (String part : parts) {
|
||||
if (!(current instanceof Map<?, ?> m)) return List.of();
|
||||
current = m.get(part);
|
||||
}
|
||||
if (current instanceof List<?> list)
|
||||
return list.stream().map(Object::toString).toList();
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private static Map<String, Object> mergeRefreshedClaims(OidcTokenResponse tokens, OidcSession old) {
|
||||
Map<String, Object> merged = new HashMap<>();
|
||||
// Fall back to old claims first, then overlay fresh token claims
|
||||
merged.putAll(old.claims());
|
||||
if (tokens.accessToken() != null)
|
||||
merged.putAll(JwtUtils.parseClaims(tokens.accessToken()));
|
||||
if (tokens.idToken() != null)
|
||||
merged.putAll(JwtUtils.parseClaims(tokens.idToken()));
|
||||
return Map.copyOf(merged);
|
||||
}
|
||||
|
||||
// -- Shared cookie utility (also used by OidcExtension) -------------------
|
||||
|
||||
static String cookieValue(Request req, String name) {
|
||||
String header = req.header("Cookie");
|
||||
if (header == null || header.isBlank()) return null;
|
||||
for (String part : header.split(";")) {
|
||||
int eq = part.indexOf('=');
|
||||
if (eq > 0 && part.substring(0, eq).strip().equals(name))
|
||||
return part.substring(eq + 1).strip();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
/**
|
||||
* OIDC provider endpoints discovered from {@code {issuer}/.well-known/openid-configuration}.
|
||||
*
|
||||
* <p>{@link #endSessionEndpoint()} may be {@code null} — not all providers expose it
|
||||
* (e.g. some Authelia configurations omit it).
|
||||
*/
|
||||
public record OidcProviderMetadata(
|
||||
String authorizationEndpoint,
|
||||
String tokenEndpoint,
|
||||
String userinfoEndpoint,
|
||||
String jwksUri,
|
||||
String endSessionEndpoint // nullable
|
||||
) {}
|
||||
@@ -0,0 +1,47 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* An authenticated user's OIDC session — persisted in {@link OidcSessionStore} and
|
||||
* looked up via the {@code oidc_session} cookie on every request.
|
||||
*
|
||||
* <p>Sessions are immutable; a refreshed access token produces a new instance
|
||||
* that replaces the old one in the store (same {@link #id()}).
|
||||
*/
|
||||
public final class OidcSession {
|
||||
|
||||
private final String id;
|
||||
private final String accessToken;
|
||||
private final String idToken;
|
||||
private final String refreshToken; // may be null
|
||||
private final Instant accessTokenExpiresAt;
|
||||
private final Map<String, Object> claims; // decoded from id_token
|
||||
|
||||
public OidcSession(String id, String accessToken, String idToken,
|
||||
String refreshToken, Instant accessTokenExpiresAt,
|
||||
Map<String, Object> claims) {
|
||||
this.id = id;
|
||||
this.accessToken = accessToken;
|
||||
this.idToken = idToken;
|
||||
this.refreshToken = refreshToken;
|
||||
this.accessTokenExpiresAt = accessTokenExpiresAt;
|
||||
this.claims = Map.copyOf(claims);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} if the access token has expired or will expire within
|
||||
* the next 30 seconds (eager refresh to avoid mid-request expiry).
|
||||
*/
|
||||
public boolean isAccessTokenExpired() {
|
||||
return Instant.now().isAfter(accessTokenExpiresAt.minusSeconds(30));
|
||||
}
|
||||
|
||||
public String id() { return id; }
|
||||
public String accessToken() { return accessToken; }
|
||||
public String idToken() { return idToken; }
|
||||
public String refreshToken() { return refreshToken; }
|
||||
public Instant accessTokenExpiresAt() { return accessTokenExpiresAt; }
|
||||
public Map<String, Object> claims() { return claims; }
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Backing store for {@link OidcSession} objects. The default implementation is
|
||||
* {@link InMemoryOidcSessionStore}; supply a custom one via
|
||||
* {@link OidcConfig.Builder#sessionStore(OidcSessionStore)} for Redis, JDBC, etc.
|
||||
*/
|
||||
public interface OidcSessionStore {
|
||||
void save(OidcSession session);
|
||||
Optional<OidcSession> find(String sessionId);
|
||||
void delete(String sessionId);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Short-lived store mapping state nonces → (original URL, PKCE verifier).
|
||||
*
|
||||
* <p>Entries expire after {@value #TTL_SECONDS} seconds. Cleanup runs on every
|
||||
* access to prevent unbounded growth without needing a background thread.
|
||||
*/
|
||||
final class OidcStateStore {
|
||||
|
||||
static final int TTL_SECONDS = 600; // 10 minutes
|
||||
|
||||
record Entry(String originalUrl, String codeVerifier, String nonce, Instant expiresAt) {}
|
||||
|
||||
private final ConcurrentHashMap<String, Entry> store = new ConcurrentHashMap<>();
|
||||
|
||||
void put(String state, String originalUrl, String codeVerifier, String nonce) {
|
||||
cleanup();
|
||||
store.put(state, new Entry(originalUrl, codeVerifier, nonce,
|
||||
Instant.now().plusSeconds(TTL_SECONDS)));
|
||||
}
|
||||
|
||||
/** Atomically retrieves and removes the entry; returns empty if absent or expired. */
|
||||
Optional<Entry> consumeAndRemove(String nonce) {
|
||||
cleanup();
|
||||
Entry e = store.remove(nonce);
|
||||
if (e == null || Instant.now().isAfter(e.expiresAt())) return Optional.empty();
|
||||
return Optional.of(e);
|
||||
}
|
||||
|
||||
private void cleanup() {
|
||||
Instant now = Instant.now();
|
||||
store.entrySet().removeIf(kv -> now.isAfter(kv.getValue().expiresAt()));
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
/** Parsed response from an OAuth2 token endpoint. Package-private — internal use only. */
|
||||
record OidcTokenResponse(
|
||||
String accessToken,
|
||||
String idToken, // may be null on refresh if provider omits it
|
||||
String refreshToken, // may be null
|
||||
int expiresIn,
|
||||
int refreshExpiresIn
|
||||
) {}
|
||||
@@ -0,0 +1,106 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Type-safe view over the JWT claims stored in {@link ClaimsHolder}.
|
||||
*
|
||||
* <p>Obtainable from any protected context via {@link ClaimsHolder#user()}.
|
||||
* Class-based handlers that extend the {@code SessionHandler} hierarchy already
|
||||
* have a provisioned DB user in {@code currentUser}; {@code OidcUser} complements
|
||||
* that by giving access to the raw OIDC claims when needed, and is the primary
|
||||
* API for lambda routes.
|
||||
*
|
||||
* <pre>{@code
|
||||
* // Lambda route (OidcMiddleware injected):
|
||||
* app.get("/api/whoami", (req, res) -> {
|
||||
* OidcUser u = ClaimsHolder.user();
|
||||
* return Map.of("sub", u.sub(), "email", u.email(), "roles", u.roles());
|
||||
* }, oidcMw.protect());
|
||||
*
|
||||
* // Class-based handler (currentUser is the DB entity; oidcUser() for raw claims):
|
||||
* protected Object handleAuthenticated(Request req, Response res) throws Exception {
|
||||
* OidcUser u = oidcUser(); // same as ClaimsHolder.user()
|
||||
* return json(res, currentUser); // DB entity — provisioned from OIDC sub
|
||||
* }
|
||||
* }</pre>
|
||||
*/
|
||||
public final class OidcUser {
|
||||
|
||||
private final Map<String, Object> claims;
|
||||
|
||||
OidcUser(Map<String, Object> claims) {
|
||||
this.claims = claims;
|
||||
}
|
||||
|
||||
// ── Common OIDC standard claims ───────────────────────────────────────────
|
||||
|
||||
/** Subject identifier — unique, stable user ID issued by the provider. */
|
||||
public String sub() { return str("sub"); }
|
||||
|
||||
/** User's email address ({@code email} claim). */
|
||||
public String email() { return str("email"); }
|
||||
|
||||
/** Human-readable username ({@code preferred_username} claim). */
|
||||
public String username() { return str("preferred_username"); }
|
||||
|
||||
/** Full display name ({@code name} claim). */
|
||||
public String name() { return str("name"); }
|
||||
|
||||
// ── Roles ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Extracts the roles list by traversing a dot-separated claim path.
|
||||
*
|
||||
* <p>Example paths:
|
||||
* <ul>
|
||||
* <li>{@code "realm_access.roles"} — Keycloak realm roles</li>
|
||||
* <li>{@code "resource_access.my-client.roles"} — Keycloak client roles</li>
|
||||
* <li>{@code "groups"} — Authelia / generic IdPs</li>
|
||||
* </ul>
|
||||
*
|
||||
* @return list of role strings, or an empty list if the path doesn't exist
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<String> roles(String claimPath) {
|
||||
String[] parts = claimPath.split("\\.");
|
||||
Object current = claims;
|
||||
for (String part : parts) {
|
||||
if (!(current instanceof Map<?, ?> m)) return List.of();
|
||||
current = m.get(part);
|
||||
}
|
||||
if (current instanceof List<?> list)
|
||||
return list.stream().map(Object::toString).toList();
|
||||
return List.of();
|
||||
}
|
||||
|
||||
/** Returns {@code true} if the user holds {@code role} at the given claim path. */
|
||||
public boolean hasRole(String claimPath, String role) {
|
||||
return roles(claimPath).contains(role);
|
||||
}
|
||||
|
||||
// ── Arbitrary claim access ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Returns the value of any claim, cast to {@code T}.
|
||||
*
|
||||
* @throws ClassCastException if the stored value is not assignable to {@code type}
|
||||
*/
|
||||
public <T> T claim(String key, Class<T> type) {
|
||||
return type.cast(claims.get(key));
|
||||
}
|
||||
|
||||
/** Returns the raw claim value, or {@code null} if absent. */
|
||||
public Object claim(String key) { return claims.get(key); }
|
||||
|
||||
/** Escape hatch — returns the full unmodified claims map. */
|
||||
public Map<String, Object> claims() { return claims; }
|
||||
|
||||
// ── Internals ─────────────────────────────────────────────────────────
|
||||
|
||||
private String str(String key) {
|
||||
Object v = claims.get(key);
|
||||
return v != null ? v.toString() : null;
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
/**
|
||||
* Thrown when OIDC token validation fails (signature, claims, nonce, expiry, etc.).
|
||||
* Distinct from {@link dev.relism.exceptions.HttpException}: this signals a protocol-level
|
||||
* failure, not an HTTP response — callers decide the appropriate status code.
|
||||
*/
|
||||
public final class OidcValidationException extends RuntimeException {
|
||||
public OidcValidationException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* PKCE (RFC 7636) utilities: code verifier generation and S256 challenge computation.
|
||||
* Package-private — used exclusively by {@link OidcExtension}.
|
||||
*/
|
||||
final class PkceUtils {
|
||||
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
private PkceUtils() {}
|
||||
|
||||
/**
|
||||
* Generates a cryptographically random code verifier (43 URL-safe characters,
|
||||
* per RFC 7636 §4.1 — 32 bytes encoded as unpadded Base64URL).
|
||||
*/
|
||||
static String generateVerifier() {
|
||||
byte[] bytes = new byte[32];
|
||||
RANDOM.nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the S256 code challenge: {@code BASE64URL(SHA-256(ASCII(verifier)))}.
|
||||
*/
|
||||
static String computeChallenge(String verifier) throws Exception {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest(verifier.getBytes(StandardCharsets.US_ASCII));
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Restricts a handler to callers whose JWT contains at least one of the
|
||||
* specified roles. Authentication is implicitly required — no need to combine
|
||||
* with {@link Authenticated}.
|
||||
*
|
||||
* <p>Roles are read from the claim configured in {@link OidcConfig#rolesClaimPath()}
|
||||
* (default: {@code "roles"}). Nested paths like {@code "realm_access.roles"} are
|
||||
* supported with dot notation.
|
||||
*
|
||||
* <pre>{@code
|
||||
* @Route(method = HttpMethod.DELETE, path = "/api/admin/blogs/{id}")
|
||||
* @RolesAllowed("admin")
|
||||
* public class DeleteBlog extends JacksonHandler { ... }
|
||||
*
|
||||
* // Multiple accepted roles (OR semantics — any one role is sufficient):
|
||||
* @RolesAllowed({"admin", "editor"})
|
||||
* public class UpdateBlog extends JacksonHandler { ... }
|
||||
* }</pre>
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
public @interface RolesAllowed {
|
||||
/** One or more role names. Access is granted if the caller has any of them. */
|
||||
String[] value();
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package dev.relism.ext.oidc;
|
||||
|
||||
import net.minidev.json.JSONValue;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* HTTP client for OAuth2 token endpoint operations (pure HTTP, no SDK).
|
||||
*
|
||||
* <p>Supports two client authentication methods (RFC 6749 §2.3):
|
||||
* <ul>
|
||||
* <li>{@link ClientAuthMethod#POST} — credentials in form body ({@code client_secret_post})</li>
|
||||
* <li>{@link ClientAuthMethod#BASIC} — credentials in {@code Authorization: Basic} header
|
||||
* ({@code client_secret_basic})</li>
|
||||
* </ul>
|
||||
*/
|
||||
final class TokenClient {
|
||||
|
||||
private final HttpClient http;
|
||||
private final String clientId;
|
||||
private final String clientSecret;
|
||||
private final ClientAuthMethod authMethod;
|
||||
|
||||
TokenClient(HttpClient http, OidcConfig config) {
|
||||
this.http = http;
|
||||
this.clientId = config.clientId();
|
||||
this.clientSecret = config.clientSecret();
|
||||
this.authMethod = config.clientAuthMethod();
|
||||
}
|
||||
|
||||
/** Authorization Code + PKCE exchange. */
|
||||
OidcTokenResponse exchangeCode(String tokenEndpoint,
|
||||
String code, String redirectUri,
|
||||
String codeVerifier) throws Exception {
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
params.put("grant_type", "authorization_code");
|
||||
params.put("code", code);
|
||||
params.put("redirect_uri", redirectUri);
|
||||
params.put("code_verifier", codeVerifier);
|
||||
return post(tokenEndpoint, params);
|
||||
}
|
||||
|
||||
/** Refresh token grant. */
|
||||
OidcTokenResponse refresh(String tokenEndpoint, String refreshToken) throws Exception {
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
params.put("grant_type", "refresh_token");
|
||||
params.put("refresh_token", refreshToken);
|
||||
return post(tokenEndpoint, params);
|
||||
}
|
||||
|
||||
// -- Internals ------------------------------------------------------------
|
||||
|
||||
private OidcTokenResponse post(String url, Map<String, String> params) throws Exception {
|
||||
HttpRequest.Builder req = HttpRequest.newBuilder()
|
||||
.uri(URI.create(url))
|
||||
.header("Content-Type", "application/x-www-form-urlencoded");
|
||||
|
||||
if (authMethod == ClientAuthMethod.BASIC) {
|
||||
String creds = Base64.getEncoder().encodeToString(
|
||||
(clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8));
|
||||
req.header("Authorization", "Basic " + creds);
|
||||
} else {
|
||||
params.put("client_id", clientId);
|
||||
params.put("client_secret", clientSecret);
|
||||
}
|
||||
|
||||
HttpResponse<String> resp = http.send(
|
||||
req.POST(HttpRequest.BodyPublishers.ofString(form(params))).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (resp.statusCode() < 200 || resp.statusCode() >= 300)
|
||||
throw new IllegalStateException(
|
||||
"Token endpoint [" + resp.statusCode() + "]: " + resp.body());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> json = (Map<String, Object>) JSONValue.parse(resp.body());
|
||||
|
||||
return new OidcTokenResponse(
|
||||
(String) json.get("access_token"),
|
||||
(String) json.get("id_token"),
|
||||
(String) json.get("refresh_token"),
|
||||
numInt(json, "expires_in", 300),
|
||||
numInt(json, "refresh_expires_in", 1800)
|
||||
);
|
||||
}
|
||||
|
||||
private static String form(Map<String, String> params) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
params.forEach((k, v) -> {
|
||||
if (!sb.isEmpty()) sb.append('&');
|
||||
sb.append(enc(k)).append('=').append(enc(v));
|
||||
});
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String enc(String v) {
|
||||
return URLEncoder.encode(v, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static int numInt(Map<String, Object> m, String key, int def) {
|
||||
Object v = m.get(key);
|
||||
return v instanceof Number n ? n.intValue() : def;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user