Created
July 16, 2020 18:22
-
-
Save sirosen/6b923c0854aeddc3468f423ce9c4e760 to your computer and use it in GitHub Desktop.
Java Client Credentials Grant Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* A simple example of a Client Credentials Grant against Globus Auth | |
*/ | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.io.OutputStream; | |
import javax.net.ssl.HttpsURLConnection; | |
import java.net.URL; | |
import java.util.Base64; | |
import java.nio.charset.StandardCharsets; | |
public class ClientCredentialsExample { | |
public static void main (String args[]) { | |
try { | |
// url to use | |
URL url = new URL("https://auth.globus.org/v2/oauth2/token"); | |
// create a connection for POST requests | |
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); | |
con.setRequestMethod("POST"); | |
con.setDoOutput(true); | |
// set the content-type for a form post | |
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); | |
// apply basic auth | |
String auth = "Basic " + Base64.getEncoder().encodeToString("CLIENT_ID:CLIENT_SECRET".getBytes(StandardCharsets.UTF_8)); | |
con.setRequestProperty("Authorization", auth); | |
// form formatted payload body | |
byte[] payload = "grant_type=client_credentials&scope=urn:globus:auth:scope:transfer.api.globus.org:all".getBytes(StandardCharsets.UTF_8); | |
// connect and send the payload | |
con.connect(); | |
OutputStream outstream = con.getOutputStream(); | |
outstream.write(payload); | |
int code = con.getResponseCode(); | |
System.out.println(code); | |
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){ | |
StringBuilder response = new StringBuilder(); | |
String responseLine = null; | |
while ((responseLine = br.readLine()) != null) { | |
response.append(responseLine.trim()); | |
} | |
System.out.println(response.toString()); | |
} | |
} catch (Exception e) { | |
System.err.println("uh-oh"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment