|
| 1 | +/* |
| 2 | + * MIT License |
| 3 | + * |
| 4 | + * |
| 5 | + * |
| 6 | + * Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | + * of this software and associated documentation files (the "Software"), to deal |
| 8 | + * in the Software without restriction, including without limitation the rights |
| 9 | + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | + * copies of the Software, and to permit persons to whom the Software is |
| 11 | + * furnished to do so, subject to the following conditions: |
| 12 | + * |
| 13 | + * The above copyright notice and this permission notice shall be included in all |
| 14 | + * copies or substantial portions of the Software. |
| 15 | + * |
| 16 | + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 | + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 | + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 | + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 | + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 | + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 | + * SOFTWARE. |
| 23 | + */ |
| 24 | +package hec.army.usace.hec.cwbi.auth.http.client; |
| 25 | + |
| 26 | +import mil.army.usace.hec.cwms.http.client.HttpRequestBuilderImpl; |
| 27 | +import mil.army.usace.hec.cwms.http.client.HttpRequestResponse; |
| 28 | +import mil.army.usace.hec.cwms.http.client.auth.OAuth2Token; |
| 29 | +import mil.army.usace.hec.cwms.http.client.request.HttpRequestExecutor; |
| 30 | + |
| 31 | +import java.io.IOException; |
| 32 | +import java.net.InetSocketAddress; |
| 33 | +import java.net.URI; |
| 34 | +import java.net.URISyntaxException; |
| 35 | +import java.net.URL; |
| 36 | +import java.net.URLDecoder; |
| 37 | +import java.nio.charset.StandardCharsets; |
| 38 | +import java.security.MessageDigest; |
| 39 | +import java.security.NoSuchAlgorithmException; |
| 40 | +import java.security.SecureRandom; |
| 41 | +import java.util.ArrayList; |
| 42 | +import java.util.Base64; |
| 43 | +import java.util.HashMap; |
| 44 | +import java.util.List; |
| 45 | +import java.util.Map; |
| 46 | +import java.util.concurrent.CompletableFuture; |
| 47 | +import java.util.concurrent.atomic.AtomicReference; |
| 48 | +import java.awt.Desktop; |
| 49 | +import java.awt.Desktop.Action; |
| 50 | + |
| 51 | +import com.sun.net.httpserver.HttpExchange; |
| 52 | +import com.sun.net.httpserver.HttpHandler; |
| 53 | +import com.sun.net.httpserver.HttpServer; |
| 54 | + |
| 55 | +public final class AuthCodePkceTokenRequestBuilder extends TokenRequestBuilder { |
| 56 | + |
| 57 | + @Override |
| 58 | + OAuth2Token retrieveToken() throws IOException { |
| 59 | + |
| 60 | + OAuth2Token retVal = null; |
| 61 | + // https://datatracker.ietf.org/doc/html/rfc7636#section-4.1 |
| 62 | + try { |
| 63 | + byte[] verifierBytes = new byte[128]; |
| 64 | + SecureRandom.getInstanceStrong().nextBytes(verifierBytes); |
| 65 | + Base64.Encoder b64encoder = Base64.getUrlEncoder(); |
| 66 | + final String verifier = b64encoder.encodeToString(verifierBytes); |
| 67 | + |
| 68 | + MessageDigest md = MessageDigest.getInstance("SHA-256"); |
| 69 | + final String challenge = b64encoder.encodeToString(md.digest(verifierBytes)); |
| 70 | + HttpServer server = HttpServer.create(new InetSocketAddress(0), 0); |
| 71 | + int port = server.getAddress().getPort(); |
| 72 | + String host = server.getAddress().getHostName(); |
| 73 | + final AtomicReference<String> code = new AtomicReference<>(); |
| 74 | + final AtomicReference<String> state = new AtomicReference<>(); |
| 75 | + final CompletableFuture<Void> future = new CompletableFuture<>(); |
| 76 | + |
| 77 | + server.createContext("/", new HttpHandler() { |
| 78 | + |
| 79 | + @Override |
| 80 | + public void handle(HttpExchange exchange) throws IOException { |
| 81 | + final String query = exchange.getRequestURI().getQuery(); |
| 82 | + Map<String, List<String>> parameters = new HashMap<>(); |
| 83 | + for (String pair: query.split("&")) { |
| 84 | + String[] kv = pair.split("="); |
| 85 | + String parameter = URLDecoder.decode(kv[0], StandardCharsets.UTF_8); |
| 86 | + String value = kv.length > 1 ? URLDecoder.decode(kv[1], StandardCharsets.UTF_8) : null; |
| 87 | + parameters.computeIfAbsent(parameter, p -> new ArrayList<>()).add(value); |
| 88 | + } |
| 89 | + |
| 90 | + code.set(parameters.get("code").get(0)); |
| 91 | + state.set(parameters.get("state").get(0)); |
| 92 | + future.complete(null); |
| 93 | + } |
| 94 | + |
| 95 | + }); |
| 96 | + |
| 97 | + String formBody = new UrlEncodedFormData() |
| 98 | + .addPassword("") |
| 99 | + .addGrantType("code") |
| 100 | + .addScopes("openid", "profile") |
| 101 | + .addClientId(getClientId()) |
| 102 | + .addUsername("") |
| 103 | + .addParameter("code_challenge_method", "S256") |
| 104 | + .addParameter("code_challenge", challenge) |
| 105 | + .addParameter("redirect_uri", String.format("http://%s:%d", host, port)) |
| 106 | + .buildEncodedString(); |
| 107 | + String urlStr= String.format("%s/%s", getUrl().getApiRoot(), formBody); |
| 108 | + // start server to listen |
| 109 | + if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Action.BROWSE)) { |
| 110 | + Desktop.getDesktop().browse(URI.create(urlStr)); |
| 111 | + } else { |
| 112 | + System.out.println(String.format("Paste the following into a browser to continue login: %s", urlStr)); |
| 113 | + } |
| 114 | + |
| 115 | + future.join(); |
| 116 | + System.out.println("Next steps."); |
| 117 | + |
| 118 | + |
| 119 | + } catch (NoSuchAlgorithmException ex) { |
| 120 | + throw new IOException("Unable to retrieve SecureRandom or Message Digest instance to generate verifier", ex); |
| 121 | + } |
| 122 | + |
| 123 | + return retVal; |
| 124 | + } |
| 125 | +} |
0 commit comments