// Copyright 2019 Google LLC. All rights reserved. package com.google.video.widevine.jts.httpclient; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * JTS Cloud Credentials. * * Provides Oauth2 authentication, and access/refresh tokens. */ public class Credentials { private static final List SCOPES = Arrays.asList( "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/widevine/frontend"); private static final int MIN_ACCESS_TOKEN_REFRESH_SEC = 1200; private static final Logger logger = Logger.getLogger(Credentials.class.getName()); private String credentialsJsonFile = null; private GoogleCredential googleCredential = null; private String accessToken = null; /** * Credentials Constructor. * * @param credentialsJsonFile The full path to a GCP service account json credentials file. */ public Credentials(String credentialsJsonFile) throws IOException { this.credentialsJsonFile = credentialsJsonFile; activateGoogleCredentials(); } private void activateGoogleCredentials() throws IOException { googleCredential = GoogleCredential .fromStream(new FileInputStream(credentialsJsonFile)) .createScoped(SCOPES); googleCredential.refreshToken(); } /** Provides an Oauth2 Access Token that can be used to make GCP service calls.*/ public String getAccessToken() throws IOException { if (accessToken == null || googleCredential.getExpiresInSeconds() <= MIN_ACCESS_TOKEN_REFRESH_SEC) { googleCredential.refreshToken(); accessToken = googleCredential.getAccessToken(); logger.log(Level.INFO, "Getting new access token."); } return accessToken; } }