'Error 403: The account for the specified project has been disabled' while accessing google cloud storage API from java - google-cloud-messaging

created multiple accounts, every time 1$ charged from cc.then I am able to create bucket in https://console.cloud.google.com/, after that I start accessing the bucket from my java code as bellow, then account getting blocked, I tried multiple times.
java code :
creating credentials
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
List<String> scopes = new ArrayList<String>();
scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
Credential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(
propsReaderUtil.getValue(ACCOUNT_ID_PROPERTY))
.setServiceAccountPrivateKeyFromP12File(
new File(getClass().getClassLoader().getResource(propsReaderUtil.getValue(
PRIVATE_KEY_PATH_PROPERTY)).getFile()))
.setServiceAccountScopes(scopes).build();
storage = new Storage.Builder(httpTransport, jsonFactory,
credential).setApplicationName(
propsReaderUtil.getValue(APPLICATION_NAME_PROPERTY))
.build();
uploading stream
Storage storage = getStorage();
StorageObject object = new StorageObject();
object.setBucket(bucketName);
InputStream stream = file.getInputStream();
try {
String contentType = URLConnection
.guessContentTypeFromStream(stream);
InputStreamContent content = new InputStreamContent(contentType,
stream);
Storage.Objects.Insert insert = storage.objects().insert(
bucketName, null, content);
insert.setName(file.getName());
insert.execute();
} finally {
stream.close();
}
Please let me know if I am doing something wrong, or suggest me best way to do this.
Any suggestions appreciated...
Thanks in advance...

Error 403 is an example of an error response you receive if you try to list the buckets of a non-existent project or one in which you don't have permission to list buckets.
The account associated with the project that owns the bucket or object has been disabled. Check the Google Cloud Platform Console to see if there is a problem with billing, and if not, contact account support.
More information can be found in HTTP Status and Error Codes.

Related

Youtrack and RestSharp Permissions issue

I'm trying to create a youtrack client using RestSharp. I can log in, but when I try to get a project, I receive the following response:
{"value":"You do not have permissions to read project. You are logged in as ****"}
However, when I log into YouTrack on my browser, I can access the project and make changes, etc. Attached is my code (I am using RestSharp):
var client = new RestClient(Site);
var request = new RestRequest(String.Format("rest/user/login?login={0}&password={1}", Username, Password), Method.POST);
//reuse the client
client.CookieContainer = new System.Net.CookieContainer();
IRestResponse response = client.Execute(request);
var content = response.Content;
//returns <login>ok</login> - so it's logging in
Console.WriteLine("LOGIN \n" + content);
String projectId = "PW";
request = new RestRequest(String.Format("rest/admin/project/projectId={0}", projectId), Method.GET);
response = client.Execute(request);
content = response.Content;
Console.WriteLine("Get Project: \n\n" + content);
Is there something in the code I'm missing? Or is this a YouTrack setup issue that I need to take up with my administrator?
For future reference:
I do not have permissions for the /rest/admin resources, but I do have them for /rest/issue. These permissions can be set by the system administrator, if they check the "Groups" in their dashboard.

Google BigQuery Service Account Credentials using JSON file in C# application

While Creating Service Account for Google BigQuery, There are two key file type. 1. P12 Key File 2. JSON Key File.
I can able to connect Google BigQuery with Service Account Credentials using P12 Key File by using following code.
String serviceAccountEmail = "XXXX#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"FileName.p12", "Secret Key", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { BigqueryService.Scope.Bigquery, BigqueryService.Scope.BigqueryInsertdata, BigqueryService.Scope.CloudPlatform, BigqueryService.Scope.DevstorageFullControl }
}.FromCertificate(certificate));
BigqueryService Service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "PROJECT NAME"
});
Now i am trying to connect Service Account Credentials using JSON file type, but i could not get the proper syntax for creating.
How can we connect Google BigQuery with Service Account Credentials using JSON File?
Thanks,
I got the link, Which indicates Service Account Authentication using JSON file in C# application is not yet added in Google BigQuery API, So i would like to close the question.
https://github.com/google/google-api-dotnet-client/issues/533
It is now possible (I used v 1.13.1.0 of Google APIs).
GoogleCredential credential;
using (Stream stream = new FileStream(#"C:\mykey.json", FileMode.Open, FileAccess.Read, FileShare.Read))
{
credential = GoogleCredential.FromStream(stream);
}
string[] scopes = new string[] {
BigqueryService.Scope.Bigquery,
BigqueryService.Scope.CloudPlatform,
};
credential = credential.CreateScoped(scopes);
BaseClientService.Initializer initializer = new BaseClientService.Initializer()
{
HttpClientInitializer = (IConfigurableHttpClientInitializer)credential,
ApplicationName = "My Application",
GZipEnabled = true,
};
BigqueryService service = new BigqueryService(initializer);

HTTP Post to Onedrive RestAPI

I'm trying to use C# for connecting to Onedrive Rest API platform, The URL that I need to connect is:
"asdfasdfLJLKJLKJK"
and the code I'm trying to run is as below:
using System.Net.Http;
using (var client = new HttpClient())
{
var content_new = new FormUrlEncodedContent(new[]{ new KeyValuePair<string, string>("access_token", "asdKJHKJH")});
var content = new FormUrlEncodedContent(values);
client.BaseAddress = new Uri("https://api.onedrive.com/v1.0");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response_web = await client.PostAsync("/drive", content_new);
var responseString = await response_web.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
Console.ReadLine();}
But for some odd reason it fails, also would like to know if I can read the data that PostAsync sends to the server? I mean the request URL as that might help troubleshooting too.
Looking at your request you are performing a POST operation on a drive, the OneDrive API does not support that action on the drive node.
If you are looking to create a new folder or upload a file, you'll want to perform that operation on https://api.onedrive.com/drive/root or where ever you'd like the operation to happen in the user's account.
To look up all of the supported actions and example requests see the OneDrive API resource model.

What is the easiest way to detect whether a user is logged in via google apps marketplace?

I have a web application which users log into using google oauth2.
I have a google apps marketplace listing for this application, and some portion of the google oauth2 users didn't need to grant permission to my application because their google apps domain administrator did it while installing the apps marketplace listing.
I'd like to be able to detect this second group of users, to analyze how frequently the apps marketplace listing is being used to log into my application. At the moment all google oauth2 logins look the same to my application.
Is there a simple API call I can make to find out whether the current user is in this group?
I use this code for finding out marketplace listing info for given appId and target domain:
InputStream p12File = Config.class.getResourceAsStream(Config.SERVICE_ACCOUNT_PRIVATE_KEY_RESOURCE_PATH);
PrivateKey serviceAccountPrivateKey = SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), p12File, "notasecret", "privatekey", "notasecret");
JsonFactory jsonFactory = new JacksonFactory();
HttpTransport t = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential.Builder bgc = new GoogleCredential.Builder()
.setTransport(t)
.setJsonFactory(jsonFactory)
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/appsmarketplace.license"))
.setServiceAccountPrivateKey(serviceAccountPrivateKey)
.setServiceAccountId(Config.SERVICE_ACCOUNT_ID);
GoogleCredential gc = bgc.build();
String token = gc.getAccessToken();
if(token == null) {
gc.refreshToken();
token = gc.getAccessToken();
}
HttpGet request = new HttpGet("https://www.googleapis.com/appsmarket/v2/customerLicense/" + applicationId + "/" + customerDomain);
request.setHeader("Authorization", "Bearer " + token);
DefaultHttpClient client = new DefaultHttpClient(httpParams);
HttpResponse resp = client.execute(request);
// ... read API JSON response

ArgumentException: Precondition failed.: !string.IsNullOrEmpty(authorization.RefreshToken) with Service Account for Google Admin SDK Directory access

I'm trying to access the Google Directory using a Service Account. I've fiddled with the DriveService example to get this code:
public static void Main(string[] args)
{
var service = BuildDirectoryService();
var results = service.Orgunits.List(customerID).Execute();
Console.WriteLine("OrgUnits");
foreach (var orgUnit in results.OrganizationUnits)
{
Console.WriteLine(orgUnit.Name);
}
Console.ReadKey();
}
static DirectoryService BuildDirectoryService()
{
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret",
X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
Scope = DirectoryService.Scopes.AdminDirectoryOrgunit.GetStringValue()
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
return new DirectoryService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "TestProject1",
});
}
When I run it, I get
ArgumentException: Precondition failed.: !string.IsNullOrEmpty(authorization.RefreshToken)
I'm going round in circles in the Google documentation. The only stuff I can find about RefreshTokens seems to be for when an individual is authorizing the app and the app may need to work offline. Can anyone help out or point me in the direction of the documentation that will, please.
Service Account authorization actually do not return Refresh Token - so this error makes sense. Do you know where this is coming from?
I am not too familiar with the .NET client library but having the full error trace would help.
As a longshot - The error might be a bad error -
Can you confirm that you've enabled the Admin SDK in the APIs console for this project
Can you confirm that you whitelisted that Client ID for the service account in the domain you are testing with (along with the Admin SDK scopes)
The above code will work if you replace the provider block with:
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
Scope = DirectoryService.Scopes.AdminDirectoryOrgunit.GetStringValue(),
ServiceAccountUser = SERVICE_ACCOUNT_USER //"my.admin.account#my.domain.com"
};
I had seen this in another post and tried it with my standard user account and it didn't work. Then I read something that suggested everything had to be done with an admin account. So, I created a whole new project, using my admin account, including creating a new service account, and authorising it. When I tried it, it worked. So, then I put the old service account details back in but left the admin account in. That worked, too.