Google Cloud Platform API -> "The OAuth client was deleted." Error - google-cloud-storage

I'm using the Google Cloud Platform API for Java (google-api-services-storage - v1beta2-rev39-1.17.0-rc).
For a couple of month It was working fine, but now I got the following error when I execute an operation.
I didn't found why the error appear. I checked if there is new version of the API but the v1beta2-rev39-1.17.0-rc is the last one.
The full stacktrace
2014-36-19 12:36:11.791 [qtp1800676648-24 - PUT /track_processing/process/39793ae0-f936-4ef1-9629-bd36bc5aa469] ERROR com.xxx.common.cloud_storage.GoogleCloudStorageService - Error without Json body.com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request{
"error" : "invalid_client",
"error_description" : "The OAuth client was deleted."}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.googleapis.media.MediaHttpUploader.executeCurrentRequestWithoutGZip(MediaHttpUploader.java:545) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.googleapis.media.MediaHttpUploader.executeCurrentRequest(MediaHttpUploader.java:562) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.googleapis.media.MediaHttpUploader.executeUploadInitiation(MediaHttpUploader.java:519) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.googleapis.media.MediaHttpUploader.resumableUpload(MediaHttpUploader.java:384) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.googleapis.media.MediaHttpUploader.upload(MediaHttpUploader.java:336) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:418) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343) ~[track_processing.jar:0.0.1-SNAPSHOT]
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460) ~[track_processing.jar:0.0.1-SNAPSHOT]
This is the executed code
public URL upload(final InputStream mediaStream, long mediaStreamSize, final String filename) throws IOException {
InputStreamContent mediaContent = new InputStreamContent(MediaType.APPLICATION_OCTET_STREAM, mediaStream);
if (mediaStreamSize > 0)
mediaContent.setLength(mediaStreamSize); // Only an estimate, but allows google to optimize the upload
StorageObject objectMetadata = new StorageObject().setName(filename)
.setAcl(Lists.newArrayList(new ObjectAccessControl().setEntity("allUsers").setRole("READER")))
.setContentDisposition("attachment");
Storage.Objects.Insert insertObject = client.objects()
.insert(storageConfiguration.getBucketName(),
objectMetadata,
mediaContent);
insertObject.getMediaHttpUploader()
.setProgressListener(new UploadProgressListener(mediaStreamSize > 0))
.setDisableGZipContent(true);
if (mediaContent.getLength() > 0 && mediaContent.getLength() <= 2 * 1000 * 1000) {
logger.info("{} is a small file (<2mb)", filename);
insertObject.getMediaHttpUploader().setDirectUploadEnabled(true);
}
return new URL(insertObject.execute().getSelfLink());
}
Regards,
Ignacio

This issue seems to have been resolved outside of the normal flow for a Stack Overflow question. I'm not sure if it should be deleted or just self-answered according to what the convention is. Consider this a placemarker answer to prevent this solved issue from appearing unsolved.

Related

RESTful client in Unity - validation error

I have a RESTful server created with ASP.Net and am trying to connect to it with the use of a RESTful client from Unity. GET works perfectly, however I am getting a validation error when sending a POST request. At the same time both GET and POST work when sending requests from Postman.
My Server:
[HttpPost]
public IActionResult Create(User user){
Console.WriteLine("***POST***");
Console.WriteLine(user.Id+", "+user.sex+", "+user.age);
if(!ModelState.IsValid)
return BadRequest(ModelState);
_context.Users.Add(user);
_context.SaveChanges();
return CreatedAtRoute("GetUser", new { id = user.Id }, user);
}
My client:
IEnumerator PostRequest(string uri, User user){
string u = JsonUtility.ToJson(user);
Debug.Log(u);
using (UnityWebRequest webRequest = UnityWebRequest.Post(uri, u)){
webRequest.SetRequestHeader("Content-Type","application/json");
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError || webRequest.isHttpError){
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
else{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
}
}
I was trying both with the Json conversion and writing the string on my own, also with the WWWForm, but the error stays.
The error says that it's an unknown HTTP error. When printing the returned text it says:
"One or more validation errors occurred.","status":400,"traceId":"|b95d39b7-4b773429a8f72b3c.","errors":{"$":["'%' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."]}}
On the server side it recognizes the correct method and controller, however, it doesn't even get to the first line of the method (Console.WriteLine). Then it says: "Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'".
Here're all of the server side messages:
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 POST http://localhost:5001/user application/json 53
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Create", controller = "User"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Create(TheNewestDbConnect.Data.Entities.User) on controller TheNewestDbConnect.Controllers.UserController (TheNewestDbConnect).
info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1]
Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect) in 6.680400000000001ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 11.3971ms 400 application/problem+json; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
I have no idea what is happening and how to solve it. Any help will be strongly appreciated!
Turned out I was just missing an upload handler. Adding this line solved it: webRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(JsonObject));

C# Download File from HTTP File Directory getting 401 error or 403 error

I’m trying to download several files from a local network device:
http file directory
I want to write a code that will automatically download all those .avi files to my pc drive.
I have 2 problems:
Problem 1: AUTHENTICATING using WebClient class only.
If I use WebClient class only to connect, I get a 401 Unauthorized error.
Code:
try
{
using (WebClient myWebClient = new WebClient())
{
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = new NetworkCredential("user", "pword");
String userName = "user";
String passWord = "pword";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
myWebClient.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
Console.WriteLine("Header AUTHORIZATION: "+ myWebClient.Headers[HttpRequestHeader.Authorization].ToString());
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}
Error Message: Failure to authenticate
401 Unauthorized Error
Problem 2: Was able to authenticate using WebProxy class but can’t download . Getting 403 Not found error.
Code:
try
{
using (WebClient myWebClient = new WebClient())
{
WebProxy wp = new WebProxy("http://192.168.2.72:81/sd/20170121/record000/",false);
wp.Credentials = new NetworkCredential("user","pword");
Console.WriteLine("Web Proxy: " + wp.Address);
myWebClient.UseDefaultCredentials = false;
myWebClient.Credentials = wp.Credentials;
myWebClient.Proxy = wp;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\"\n\n", filename, wp.Address);
// Download the Web resource and save it into the current filesystem folder.
Console.WriteLine("Start DL");
myWebClient.DownloadFile("http://192.168.2.72:81/sd/20170121/record000/P170121_000000_001006.avi", "P170121_000000_001006.avi");
Console.WriteLine("End DL");
}
}
catch(Exception ex)
{
Console.WriteLine("DOWNLOAD ERROR: " + ex.ToString());
}
Error Message: 403 Not Found
DOWNLOAD ERROR: System.Net.WebException: The remote server returned an error: (404) Not Found.
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at System.Net.WebClient.DownloadFile(String address, String fileName)
at ConsoleApplication2.Program.Main(String[] args) in C:\Users\Gordon\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 139
Please help me identify if there are any mistakes in my code or is there a better way to submit credentials and download all the files.
Thanks in advance!
I'm not Dot Net developer, I'm just sharing my opinion.
In the second point you have mentioned that you are getting 403 which is the Http status code for Acces Denied. I feel your credentials are not valid or you don't have privilege to do the operation.

PayPal Sandbox API SSL handshake error HTTPS request

With new changes in paypal , it started throwing SSL handshake exceptions those who are using old system. "PayPal SSL Certificate Changes"
https://devblog.paypal.com/paypal-ssl-certificate-changes/
This may help someone. After i got SSL Handshake exception , i spent a hell lot of time to resolve it.
Here is the Exception :
javax.net.ssl.SSLHandshakeException: Received fatal alert:
handshake_failure
Solution :
Requirements to resolve this issue :
Start from Jan 19, all sandbox API endpoint need to
1.) Use TLS 1.2 and HTTP/1.1 connection
2.) Upgrade to SHA-256 and use the G5 root certificate to make the HTTPS connection
Point 1 Solution:
If you are using java 6 then better upgrade it to java 7
https://blogs.oracle.com/java-platform-group/entry/diagnosing_tls_ssl_and_https
For my case i am using java 7 so TLSv1 (default) for JDK 7.
We have to enable it manually while starting server
**-Dhttps.protocols=TLSv1.2** passed as vm argument.
Point 2 Solution :
https://knowledge.verisign.com/support/mpki-for-ssl-support/index?page=content&actp=CROSSLINK&id=SO5624
G5 cerificate import: Save it as test.cer
Go to java home/bin then run this command
keytool -importcert -file C:/test.cer
create sanbox account. Get the facilator password and signature pass it as parameters
String encodedData = "USER=XXX-facilitator_api1.XXX.XXX"
+ "&PWD=XXXXXXXXXXXX"
+ "&SIGNATURE=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-"
+ "&VERSION=95"
+ "&METHOD=SetExpressCheckout"
+ "&PAYMENTREQUEST_0_PAYMENTACTION=Authorization"
+ "&L_PAYMENTREQUEST_0_NAME0="+URLEncoder.encode("Testing","UTF-8")
+ "&L_PAYMENTREQUEST_0_DESC0="+URLEncoder.encode("Testing","UTF-8")
+ "&L_PAYMENTREQUEST_0_AMT0="+URLEncoder.encode("99","UTF-8")
+ "&PAYMENTREQUEST_0_AMT="+URLEncoder.encode("99","UTF-8")
+ "&PAYMENTREQUEST_0_CURRENCYCODE="+URLEncoder.encode("USD","UTF-8")
+ "&LOCALECODE=en_GB"
+ "&RETURNURL=google.com"
+ "&CANCELURL=google.co.in"
+ "&LOGOIMG=imageurl";
String responsepaypal = getHTMLcontent("https://api-3t.sandbox.paypal.com/nvp",encodedData ,"UTF-8");
String token = responsepaypal.toString().replaceAll("TOKEN=(.*?)&TIMESTAMP.*", "$1");//***Token for post request on paypal***
public static String getHTMLcontent(String url,String urlParameters, String encodingDef) throws IOException {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(urlParameters.length()));
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36");
con.setRequestProperty("Host", "api-3t.sandbox.paypal.com");
con.setRequestProperty("Upgrade-Insecure-Requests", "1");
con.setRequestProperty("Pragma", "no-cache");
//con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
con.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.setRequestProperty("Connection", "keep-alive");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(urlParameters);
output.close();
DataInputStream input = new DataInputStream( con.getInputStream() );
StringBuffer sb = new StringBuffer();
String line;
while ((line = input.readLine()) != null) {
sb.append(line);
}
input.close();
return sb.toString();
}}
Follow the steps out here clearly mentioned:
https://developer.paypal.com/docs/classic/express-checkout/ht_ec-singleAuthPayment-curl-etc/
I was testing paypal using the sandbox account and I was getting the same error. I upgraded to java 8 and the error was not there anymore.

SocketIO4Net Handshake Error

I've got a problem with the connection of a client to a socket.io server.
I have following code:
private Client _Client;
private void Initialize(string websocket)
{
try
{
this._Client = new Client(websocket);
this._Client.Connect();
if (!this._Client.IsConnected) throw new Exception("Connection to websocket wasn't successfully: " + this._Client.HandShake.ErrorMessage);
}
catch (Exception ex)
{
Logging.Write("Fehler bei der SocketIO-Connection: " + ex.Message);
Logging.WriteLine("incomplete!", ConsoleColor.Red);
return;
}
Logging.WriteLine("completed!", ConsoleColor.Green);
}
I'm using the websocket-uri
http://127.0.0.1:5116/
When I open that address in browser, it shows me the right socket.io socketserver.
At connection to this socket.io server I get the following error:
Error getting handsake from Socket.IO host instance:
Der Remoteserver hat einen Fehler zurückgegeben: (400) Ungültige Anforderung.
So it is a http error (400) bad request. But why?
What can I do? I just tried the following code (a solution from a user from a other question):
System.Net.WebRequest.DefaultWebProxy = null;
But that didn't work for me.
I fixed this error by myself.
It was very simple. The handshake of the socket.io version 1.0.x isn't the same as in version 0.9.x. And SocketIO4Net only working with socket.io version 0.9.x. I downgraded to version 0.9.17 and now it's working perfectly :)

Google authentication

I got a problem on google authenticate, it worked for a month but since a few days I got this error :
Fatal error: Uncaught exception 'apiAuthException' with message
'Invalid token format' in /home/project/html/google/auth/apiOAuth2.php:127 Stack trace:
#0 /home/project/html/google/auth/apiOAuth2.php(89): apiOAuth2->setAccessToken('{? "access_tok...')
#1 /home/project/html/google/apiClient.php(132): apiOAuth2->authenticate(Array)
#2 /home/project/html/hk/connects/google.php(22): apiClient->authenticate()
#3 {main} thrown in /home/project/html/google/auth/apiOAuth2.php on line 127
In apiOAuth2.php I have the code :
$accessToken = json_decode($accessToken, true);
if (! isset($accessToken['access_token']) || ! isset($accessToken['expires_in']) || ! isset($accessToken['refresh_token'])) {
throw new apiAuthException("Invalid token format");
}
I noticed that google doesn't send me the $accessToken['refresh_token'].
It doesn't seem to come from google cause I did a correct connexion on http://stackoverflow.com
Maybe it's cause of my code :
session_start();
$client = new apiClient();
$plus = new apiPlusService($client);
if (!isset($_GET['code'])) {
header('Location: '.$client->createAuthUrl()); // Calls the same page
} else {
$client->authenticate(); // Fails at this level
}
EDIT:
I figured a way to do it, like I don't know what is refresh_token made for I added this line :
if (!isset($accessToken['refresh_token'])) $accessToken['refresh_token'] = 12345678910;
It works for the moment...
There is a new explicit parameter called "access_type" required by the google authentication api to obtain a valid refresh token.
With this parameter you declare that you need offline access to the account and the api provides you a refresh token.
Download the latest google PHP SDK that automatically handles the new required parameter