Invalid Redirect URL in Google Drive - google-drive-api

When i am entering http://mydomain.com in Google Drive Redirect URL then getting:
Invalid Redirect URL
Please let me know what is the issue ?

I am referring to the console, where you create and get your keys for your projects:
https://cloud.google.com/console
Your URL to localhost is the box "Redirect URIs"
In your code, then you have:
$redirectURI = 'http://localhost';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectURI);
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
These must match, or you'll get this error every time.

Related

GAS Wialon Local Remote API: Retrieve login data

Good day,
I have a Wialon Local server (GPS monitoring system) and am planning to update a shared Google sheet using time-driven installable triggers.
As per the Wialon documentation, I am able to get the desired response when entering my API call in a browser.
However, in GAS, I am getting the below error when trying to retrieve data from the response.
API Call:
let apiURL = `http://my.tracking.site.come/wialon/ajax.html?svc=token/login&params={"token":"5dce19710a5e26ab8b7b898XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXFCEED7DC03BC48FF5F8"}`
console.log(apiURL) // This URL works in a web browser as expected
var resText = UrlFetchApp.fetch(apiURL).getContentText() // error is raised on this line
console.log(resText)
The error:
11:48:27 AM Error
Exception: Invalid argument: http://my.tracking.site.come/wialon/ajax.html?svc=token/login&params={"token":"5dce19710a5e26ab8b7b898XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXFCEED7DC03BC48FF5F8"}
wialonLogin # wialon.gs:20
Kindly advise what I am doing wrong here as I have very little experience with both GAS and Wialon Remote API ... will appreciate any assitance.
Thanks.
Solution is to encode the URL.
let apiURL = `http://my.tracking.site.come/wialon/ajax.html?svc=token/login&params={"token":"5dce19710a5e26ab8b7b898XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXFCEED7DC03BC48FF5F8"}`
console.log(apiURL) // This URL works in a web browser as expected
var urlEncoded = encodeURI(apiURL);
var resText = UrlFetchApp.fetch(urlEncoded).getContentText() // error is raised on this line
console.log(resText)

Whats redirect URI in freelancer api OAuth?

I cannot understand how this works:
from flask import Flask, redirect
oauth_uri = 'https://accounts.freelancer.com/oauth/authorise'
client_id = '<CLIENT_ID>'
redirect_uri = '<CLIENT_REDIRECT_URI>'
prompt = 'select_account consent'
advanced_scopes = '1 3'
app = Flask(__name__)
# Users who hit this endpoint will be redirected to the authorisation prompt
#app.route('/authorize')
def handle_authorize():
return redirect(
'{0}?response_type=code'
'&client_id={1}&redirect_uri={2}'
'&scope=basic&prompt={3}'
'&advanced_scopes={4}'.format(
oauth_uri, client_id, redirect_uri, prompt, advanced_scopes
)
)
This code gives me : Invalid redirect URI in browser.
Whats this redirect URI, why can't I give any redirect uri of my choice?
Its documented here: can anyone please explain to me how this works,
https://developers.freelancer.com/docs/authentication/generating-access-tokens#header-receive-authorisation-response
The redirect URL is the URL you set for your application on your apps dashboard. You need to specify a valid URL for Freelancer.com to redirect to after the user has granted access for your app. Think of how Facebook grants access to third party apps using their log in system.

Accessing Google API from a web application

I've been trying for a couple of days now to crack this but have not had any success.
I have a web application that I want to use with Google Drives API.
I want the web application to check if there is an access token it can use and if not redirect to Google so the user can log in and grant access.
Seemingly a simple task but it's driving me mad! I've checked the Google documentation but it all seems to be geared around console applications
Google provides an interface UserService which stores details of the users using the application. If the users is not logged in redirect the user to login page using:
response.sendRedirect(userService.createLoginURL(request.getRequestURI()))
Later or if the user is logged in, redirect him to "Request for Permission" page using:
List<String> scopes = Arrays.asList(PlusScopes.PLUS_LOGIN,PlusScopes.PLUS_ME,PlusScopes.USERINFO_EMAIL,PlusScopes.USERINFO_PROFILE......); // Add/remove scopes as per your requirement
List<String> responseTypes = Arrays.asList("code");
GoogleAuthorizationCodeRequestUrl gAuthCode = new GoogleAuthorizationCodeRequestUrl(Google project client id, redirect url, scopes);
gAuthCode.setAccessType("offline");
gAuthCode.setClientId(Google project client id);
gAuthCode.setResponseTypes(responseTypes);
gAuthCode.setApprovalPrompt("force");
authURl = gAuthCode.toURL().toString();
response.sendRedirect(authURl);
Make sure you add all required scopes of the API methods you will be using. After the user has accepted, you will have to create a servlet with "/oauth2callback" mapping to get the authorization code.
request.getParameter("code")
In the same servlet using the code obtained, get refresh and access token making a rest call.
URL url = new URL("https://www.googleapis.com/oauth2/v3/token");
HttpURLConnection connection= (HttpURLConnection)url.openConnection();
connection.setRequestMethod("post");
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream dw= new DataOutputStream(connection.getOutputStream());
dw.writeBytes("code="+authorizationCode+"&client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET+"&redirect_uri="+REDIRECT_URL+"&grant_type=authorization_code");
dw.flush();
dw.close();
InputStream inputStream= connection.getInputStream();
Parse the input stream to get your refresh token and access token and redirect the user to your landing page.
Now you have access token to query your api whose scopes were provided in authorization flow. Also you have a refresh token which can be used to regenerate new access token if the previously issued access token has expired.
You should be able to implement the OAuthHandshake using HTTP requests and a redirect URL to your web application. You can play around with the requests here to see what the headers and responses look like: https://developers.google.com/oauthplayground/
You can store the authorization code and tokens any way you like. You would have your web application refer to these tokens to see if they are expired. For example:
def getTokenFromFile(self):
creds = self.readCredsFromDisk()
# check if token is expired
expiration_time = datetime.datetime.strptime(creds['token_expiry'], '"%Y-%m-%dT%H:%M:%S.%f"')
if expiration_time < datetime.datetime.now():
self.refreshToken()
# reload creds
creds = self.readCredsFromDisk()
return creds['access_token']
I'm writing just a python script that does the handshake and saves the token to a plain text file. Any time the script runs a function to the Google API it will use this function.
The refresh function:
def refreshToken(self):
with open('client_secret.json') as s:
secret = json.load(s)
secret = secret['installed']
creds = self.readCredsFromDisk()
refresh_url = secret['token_uri']
post_data = {'client_id':secret['client_id'],
'client_secret':secret['client_secret'],
'refresh_token':creds['refresh_token'],
'grant_type':'refresh_token'}
headers = {'Content-type':'application/x-www-form-urlencoded'}
(resp, content) = self.http.request(refresh_url,
method='POST',
body=urlencode(post_data),
headers=headers)
content = json.loads(content)
creds['access_token'] = content['access_token']
date = datetime.datetime.now() + datetime.timedelta(seconds=content['expires_in'])
creds['token_expiry'] = json.dumps(date.isoformat())
self.writeCredsToDisk(json.dumps(creds))
You would write a function similar to this to trade the original authorization code and access code following the logic the OAuth Playground shows you.

Google Drive API get file Edit URL

As of 04/20/2015 the Google Documents API v3.0 is deprecated, and will no longer function function on and after this date. So anyone using this API must switch to use the Google Drive API.
I have integrated the Google Drive API into my PHP application, but I can not find how to get a EDIT url for a file I have created or uploaded. Previously in the Google Documents API after uploading a file, the response would return a edit url that would be a direct url to edit the file.
I am using a service account that uses a generated key by my google developers account at https://console.developers.google.com. This means my application is making calls on behalf of my service account the developer account has created for me. A google drive service account CAN NOT be accesses by the Drive UI, because as a user you can not login to the account as you would a personal google account.
What I have done is shared my documents I have uploaded or created with my personal account, and the url google returns in the call is named "alternateLink" and it is formatted as such:
https://docs.google.com/file/d/0B0nkjw07ekP9LUpuZG4tOHcxdkE/edit?usp=drivesdk
However when logged into the account I shared the above file with, it just goes to a viewer and not the "Google Docs Editor"
How can I get a file's edit link with Google Drive API?
The link you are using is correct, so that's not the issue.
The main problem was you have to set convert true in the time of upload. Without converting the file google will give you the link to view not to edit.
Here you will get file upload detials. Please check the below code i have only added the convert field:-
$file = new Google_Service_Drive_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
'convert' => true // To convert you file
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
The AlternateLink is the edit url, and my issue was the uploadType value and the mime-type for the document type when attempting to upload or create the document with the google drive api.
The file edit URL can be found under the WebViewLink file property. You can retrieve it by doing something like:
$sheetsList = $drive_service->files->listFiles([
'fields' => 'files(id, name, webViewLink, webContentLink)',
]);
// You could be using $seetList->getFiles() to loop through the files.
// Here we're just picking the current one (any file) to get the WebViewLink for.
print $sheetsList->current()->getWebViewLink();
In order to adjust file permissions you can use:
$permissions = new \Google_Service_Drive_Permission();
$permissions->setRole('writer');
$permissions->setType('anyone');
$drive_service->permissions->create($file_id, $permissions);
Possible values for setRole() and setType() can be found here: https://developers.google.com/drive/api/v3/reference/permissions/create

Cannot access the Box Application using API Key

I have created an application in Box and got an API Key, and then edited the redirect URL. But when I accessed through URL https://www.box.net/api/1.0/rest?action=get_ticket&api_key=APIKEY, I'm not getting a positive response, instead of I'm getting a response like:
<response>
<status>application_restricted</status>
</response>
Please provide me a solution to get access to the application.
Thanks in advance.
The V1 API has been deprecated and will no longer provide authentication or file access. You need to migrate your application to the V2 API, which is documented here.
For accessing access_token using java sdk , You need to have following key values
1) clienId > Use Application console
2) client_secret > Use application console
3) code > Code value you will get using below link
https://account.box.com/api/oauth2/authorize?response_type=code&client_id={your_client_id}&state=security_token%3DKnhMJatFipTAnM0nHlZA
Replace your client id with original value. client id you will get from your apps.
And Follow steps and authorize you application using your credential.
after that it will redirect to https://localhost/?state=security_token%3DKnhMJatFipTAnM0nHlZA&code=sdsdsd3sdsdC0oGqOS2WgaFipZBdj
Copy code value
String clienId = "your client id ";
String client_secret = "your secret id";
String code = "sdsdsd3sdsdC0oGqOS2WgaFipZBdj"; // use above extracted code value
BoxAPIConnection con = new BoxAPIConnection(clienId,client_secret,code);
String accessToken = con.getAccessToken();
System.out.println("Accss_Token : " +accessToken);