Reputation: 83
I'm trying to get data from Reports API.
I get access token for service account and using it in GET request. Response always
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Access denied. You are not authorized to read activity records.",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Access denied. You are not authorized to read activity records."
}
}
I'm using Java for request. Without Google API library (client requirement). Source code is
String urlString = "https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/drive?maxResults=25";
URL url = new URL(urlString);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
// optional default is GET
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
// Add request header.
urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken.getValue());
int responseCode = urlConnection.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + urlString);
System.out.println("Response Code : " + responseCode);
BufferedReader bufferedReader;
if (responseCode == 200) {
bufferedReader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
} else {
bufferedReader = new BufferedReader(
new InputStreamReader(urlConnection.getErrorStream()));
}
String inputLine;
StringBuffer stringBuffer = new StringBuffer();
while ((inputLine = bufferedReader.readLine()) != null) {
stringBuffer.append(inputLine);
}
bufferedReader.close();
System.out.println(stringBuffer.toString());
Can you, please, help me what I'm missing?
Regards, Aleks.
Upvotes: 3
Views: 6150
Reputation: 81
For those who are using the Java client and come across this issue, you have to
.createDelegated("[email protected]")
to the method chain for creating the GoogleCredential object
I also was getting the 401 until i found the reference for step 3.
Now i can call into the Reports API with this code
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport()
JsonFactory jsonFactory = GsonFactory.getDefaultInstance()
List<String> SCOPES = Collections.singletonList(ReportsScopes.ADMIN_REPORTS_AUDIT_READONLY)
GoogleCredentials googleCredentials = GoogleCredentials
.fromStream(new FileInputStream(googleApiKey))
.createScoped(SCOPES)
.createDelegated("[email protected]")
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(googleCredentials)
new Reports.Builder(httpTransport, jsonFactory, requestInitializer)
.setApplicationName("some-project-id")
.build()
Upvotes: 0
Reputation: 540
Just the below code. Two things are very important here: email-id i.e. SERVICE_ACCOUNT_EMAIL and json file SERVICE_ACCOUNT_PKCS12_FILE_PATH:
Source: https://developers.google.com/admin-sdk/reports/v1/guides/delegation
I am using the the GO version of it and it works like a charm after spending 2 days on it :)) (by the way GO version can be found here: https://developers.google.com/admin-sdk/directory/v1/guides/delegation#go)
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.admin.reports.Reports;
import com.google.api.services.admin.reports.ReportsScopes;
...
/** Email of the Service Account */
private static final String SERVICE_ACCOUNT_EMAIL = "<some-id>@developer.gserviceaccount.com";
/** Path to the Service Account's Private Key file */
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/path/to/<public_key_fingerprint>-privatekey.p12";
/**
* Build and returns a Reports service object authorized with the service accounts
* that act on behalf of the given user.
*
* @param userEmail The email of the user. Needs permissions to access the Admin APIs.
* @return Reports service object that is ready to make requests.
*/
public static Reports getReportsService(String userEmail) throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(ReportsScopes.ADMIN_REPORTS_AUDIT_READONLY)
.setServiceAccountUser(userEmail)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
Reports service = new Reports.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).build();
return service;
}
Upvotes: 0
Reputation: 117016
"Access denied. You are not authorized to read activity records.",
means just that the user you are authecated with does not have access to do what you are trying to do. To use a service account with this api you need to set up domain wide delegation
In enterprise applications you may want to programmatically access a user's data without any manual authorization on their part. In G Suite domains, the domain administrator can grant third-party applications with domain-wide access to its users' data — this is referred as domain-wide delegation of authority. To delegate authority this way, domain administrators can use service accounts with OAuth 2.0.
- Go to your G Suite domain’s Admin console.
- Select Security from the list of controls. If you don't see Security listed, select More controls from the gray bar at the bottom of the page, then select Security from the list of controls.
- Select Advanced settings from the list of options.
- Select Manage third party OAuth Client access in the Authentication section.
- In the Client name field enter the service account's Client ID.
- In the One or More API Scopes field enter the list of scopes that your application should be granted access to (see image below). For example if you need domain-wide access to activity reports enter: https://www.googleapis.com/auth/admin.reports.audit.readonly
- Click the Authorize button.
Upvotes: 3