001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.rest.auth.oauth.flow; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020 021import java.io.*; 022import java.time.*; 023import java.util.*; 024import java.util.function.*; 025 026import com.nimbusds.oauth2.sdk.*; 027import com.nimbusds.oauth2.sdk.http.*; 028 029/** 030 * Helpers shared across all flow types. 031 * 032 * <p> 033 * Centralizes the Nimbus {@code TokenRequest}-to-{@code OAuthToken} round-trip plus the standard error mapping. 034 * 035 * @since 10.0.0 036 */ 037public final class Flows { 038 039 /** Default connect/read timeout applied to every token-endpoint request when the caller sets none. */ 040 static final Duration DEFAULT_HTTP_TIMEOUT = Duration.ofSeconds(10); 041 042 private Flows() {} 043 044 /** 045 * Sends the supplied {@link TokenRequest} via Nimbus's HTTP client and maps the response to 046 * {@link OAuthToken}. 047 * 048 * <p> 049 * A finite connect/read timeout is applied BEFORE the caller's {@code httpConfigurator} runs, so an unresponsive 050 * IdP can never wedge the call indefinitely while still letting callers override the value. 051 * 052 * @param req The Nimbus {@code TokenRequest}. Never {@code null}. 053 * @param timeout The connect/read timeout. {@code null} selects {@link #DEFAULT_HTTP_TIMEOUT}. 054 * @param httpConfigurator Optional pre-send hook on the {@link HTTPRequest}. 055 * @return The acquired token. 056 * @throws OAuthFlowException If the IdP returns an error or the HTTP round-trip fails. 057 */ 058 public static OAuthToken send(TokenRequest req, Duration timeout, Consumer<HTTPRequest> httpConfigurator) { 059 var http = req.toHTTPRequest(); 060 applyTimeout(http, timeout); 061 if (httpConfigurator != null) 062 httpConfigurator.accept(http); 063 HTTPResponse httpResp; 064 try { 065 httpResp = http.send(); 066 } catch (IOException e) { 067 throw new OAuthFlowException("OAuth token endpoint HTTP call failed", e); 068 } 069 TokenResponse resp; 070 try { 071 resp = TokenResponse.parse(httpResp); 072 } catch (ParseException e) { 073 throw new OAuthFlowException("OAuth token-endpoint response could not be parsed", e); 074 } 075 if (!resp.indicatesSuccess()) { 076 var err = resp.toErrorResponse().getErrorObject(); 077 var code = (err == null || err.getCode() == null) ? "unknown_error" : err.getCode(); 078 throw new OAuthFlowException("OAuth token endpoint error: " + code, code); 079 } 080 return toOAuthToken(resp.toSuccessResponse()); 081 } 082 083 /** 084 * Applies a finite connect/read timeout to a Nimbus {@link HTTPRequest} (Nimbus defaults to infinite). 085 * 086 * @param http The request. Never {@code null}. 087 * @param timeout The timeout. {@code null} selects {@link #DEFAULT_HTTP_TIMEOUT}. 088 */ 089 static void applyTimeout(HTTPRequest http, Duration timeout) { 090 var t = timeout == null ? DEFAULT_HTTP_TIMEOUT : timeout; 091 var ms = (int) Math.min(t.toMillis(), Integer.MAX_VALUE); 092 http.setConnectTimeout(ms); 093 http.setReadTimeout(ms); 094 } 095 096 private static OAuthToken toOAuthToken(AccessTokenResponse success) { 097 var tokens = success.getTokens(); 098 var access = tokens.getAccessToken(); 099 String tokenType = access.getType() != null ? access.getType().getValue() : "Bearer"; // HTT: null branch unreachable; Nimbus AccessToken always has a non-null AccessTokenType 100 Instant expiresAt = computeExpiry(access); 101 Optional<String> refreshToken = tokens.getRefreshToken() != null 102 ? o(tokens.getRefreshToken().getValue()) 103 : oe(); 104 Optional<Set<String>> scope = access.getScope() != null 105 ? o(new LinkedHashSet<>(access.getScope().toStringList())) 106 : oe(); 107 Optional<String> idToken = oe(); 108 var custom = success.getCustomParameters(); 109 var v = custom.get("id_token"); 110 if (v instanceof String v2) 111 idToken = o(v2); 112 return new OAuthToken(access.getValue(), tokenType, expiresAt, refreshToken, scope, idToken); 113 } 114 115 private static Instant computeExpiry(com.nimbusds.oauth2.sdk.token.AccessToken access) { 116 var lifetime = access.getLifetime(); 117 if (lifetime <= 0L) 118 return Instant.MAX; 119 return Instant.now().plusSeconds(lifetime); 120 } 121}