1 /* 2 * Copyright 2022 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 // [START auth_cloud_idtoken_metadata_server] 18 19 import com.google.auth.oauth2.GoogleCredentials; 20 import com.google.auth.oauth2.IdTokenCredentials; 21 import com.google.auth.oauth2.IdTokenProvider; 22 import com.google.auth.oauth2.IdTokenProvider.Option; 23 import java.io.IOException; 24 import java.security.GeneralSecurityException; 25 import java.util.Arrays; 26 27 public class IdTokenFromMetadataServer { 28 main(String[] args)29 public static void main(String[] args) throws IOException, GeneralSecurityException { 30 // TODO(Developer): Replace the below variables before running the code. 31 32 // The url or target audience to obtain the ID token for. 33 String url = "https://example.com"; 34 35 getIdTokenFromMetadataServer(url); 36 } 37 38 // Use the Google Cloud metadata server to create an identity token and add it to the 39 // HTTP request as part of an Authorization header. getIdTokenFromMetadataServer(String url)40 public static void getIdTokenFromMetadataServer(String url) throws IOException { 41 // Construct the GoogleCredentials object which obtains the default configuration from your 42 // working environment. 43 GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault(); 44 45 IdTokenCredentials idTokenCredentials = 46 IdTokenCredentials.newBuilder() 47 .setIdTokenProvider((IdTokenProvider) googleCredentials) 48 .setTargetAudience(url) 49 // Setting the ID token options. 50 .setOptions(Arrays.asList(Option.FORMAT_FULL, Option.LICENSES_TRUE)) 51 .build(); 52 53 // Get the ID token. 54 // Once you've obtained the ID token, you can use it to make an authenticated call to the 55 // target audience. 56 String idToken = idTokenCredentials.refreshAccessToken().getTokenValue(); 57 System.out.println("Generated ID token."); 58 } 59 } 60 // [END auth_cloud_idtoken_metadata_server] 61