How can I get a token for the Drive API? - node.js

I want to implement the Google Drive API to my web application using NodeJS and I'm struggling when I try to get a token via OAuth.
I've copied the code from this guide and run the script using Node and it returns an error in this line:
var redirectUrl = credentials.installed.redirect_uris[0];
Googling around I found that I can set that variable as http://localhost:8080 and set the same value in the Authorized redirect URIs configuration in the Google Developers Console and that error goes away, fine, it works. Now it asks for a code that I should get by using an URL.
https://accounts.google.com/o/oauth2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly&response_type=code&client_id=CLIENT_ID&redirect_uri=http%3A%2F%2Flocalhost%3A8080
Then I've added the client id and enter to that URL with Chrome and then returns a connection refused error. No clue what to do in here, I searched about my problem and I can't found an answer. By looking at the direction bar in Chrome I see that there's a parameter called code and after it, there's random numbers and letters. Like this:
http://localhost:8080/?code=#/r6ntY87F8DAfhsdfadf78F7D765lJu_Vk-5qhc#
If I add any of these values it returns this error...
Error while trying to retrieve access token { [Error: invalid_request] code: 400 }
Any ideas on what should I do? Thanks.

Did you follow all the directions on the page you indicated, including all of those in Step 1 where you create the credentials in the console and download the JSON for it? There are a few things to note about creating those credentials and the JSON that you get from it:
The steps they give are a little different from what I went through. They're essentially correct, but the "Go to credentials" didn't put me on the page that has the "OAuth Consent Screen" and "Credentials" tabs on the top. I had to click on the "Credentials" left navigation for the project first.
Similarly, on the "Credentials" page, my button was labeled "Create Credentials", not "Add Credentials". But it was a blue button on the top of the page either way.
It is very important that you select "OAuth Client ID" and then Application Type of "Other". This will let you create an OAuth token that runs through an application and not through a server.
Take a look at the client_secret.json file it tells you to download. In there, you should see an entry that looks something like "redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"] which is the JSON entry that the line you reported having problems with was looking for.
That "urn:ietf:wg:oauth:2.0:oob" is a magic string that says that you're not going to redirect anywhere as part of the auth stage in your browser, but instead you're going to get back a code on the page that you will enter into the application.
I suspect that the "connection refused" error you're talking about is that you used "http://localhost:8080/" for that value, so it was trying to redirect your browser to an application running on localhost... and I suspect you didn't have anything running there.
The application will prompt you to enter the code, will convert the code into the tokens it needs, and then save the tokens for future use. See the getNewToken() function in the sample code for where and how it does all this.

You need to use this code to exchange for a token. I'm not sure with nodejs how to go about this but in PHP I would post the details to the token exchange url. In javascript you post array would look similar to this ....
var query = {'code': 'the code sent',
'client_id': 'your client id',
'client_secret': 'your client secret',
'redirect_uri': 'your redirect',
'grant_type': 'code' };
Hope this helps

Change redirect uri from http://localhost:8080 to https://localhost:8080.
For this add SSL certificates to your server.

Related

passport-apple inexplainable invalid_client on nodejs backend -- using clean example repository with fresh set of credentials

I've cloned https://github.com/ananay/passport-apple-example and replaced the config with this:
clientID: "com.myname.web",
teamID: "myteamid",
callbackURL: "https://myurldev.com/auth/apple/redirect",
keyID: "mykeyid",
privateKeyLocation: path.join(__dirname, "../apple-key.p8")
I've also added SSL certificate on my machine and starting the server with https, all works fine & is recognized by my browser. I'm also starting the app on port 443 and proxying using my hosts file myurl.dev.com -> 127.0.0.1.
I have the same auth setup for facebook, google & microsoft and everything works fine.
I have:
Created a new APP identifier and enabled Sign in with Apple for it, named it: com.myname.dev
Created a new SERVICE identifier and enabled Sign in with apple, called it: com.myname.web
Added "https://myurldev.com/auth/apple/redirect" to the "Reply URLS" on the service identifier com.myname.web
Set my app identifier com.myname.dev as the main app identifier my service to be grouped with.
Created a private key and enabled sign in with apple, interface confirmed the presence of grouped ID com.myname.web bundled with com.myname.dev for which the key was created.
I have confirmed using console.log that the private key is indeed at the path being passed as parameter.
converted the .p8 file to base64 & then back to UTF-8 in an attempt to use the string for privateKeyString
successfully implemented Apple Oauth several times in the past using passport-apple
This time around, for some reason, auth simply doesn't work.
If I set the clientID as the APP identifier, not the service, I'm getting
invalid_request
Invalid web redirect url.
instead of invalid_client
Any advice on debugging this is highly appreciated. Thank you.
EDIT #1:
I have dug a bit deeper into the passport-apple package to figure out if anything goes against apple's docs around token generation, but the flow never reaches that part, indicating things go wrong on the actual configuration in Apple's console & what I'm trying to use for my project.
EDIT #2
2 of the app Ids I have created always throw "wrong redirect uri" because they're not service IDs so I can't configure redirect_uri, this will change if to "required" if I pass undefined as a redirect_uri.
One of the app ids throws only invalid client_id instead, regardless if I pass undefined or good value for redirect_uri.
EDIT #3
Went full vanilla through the OAuth code flow process and just created a url & redirected the user it, failing with this method is consistent with what is happening when using the passport-apple module.
const url = new URL("https://appleid.apple.com/auth/authorize");
url.searchParams.append("state", "fdbd287b1f");
url.searchParams.append("response_type", "code");
url.searchParams.append("scope", "name email");
url.searchParams.append("response_mode", "form_post");
url.searchParams.append(
"redirect_uri",
"https://raiseitupdev.com/auth/apple/redirect",
);
url.searchParams.append("client_id", "com.myname.web");
return res.redirect(url.toString());
[Creator of the library here.]
Did it stop working in development too? I feel this is a configuration error because the actual thing is working live on my website:
https://passport-apple.ananay.dev
Please follow up on this Github issue. Thanks!
https://github.com/ananay/passport-apple/issues/23

How to fill login prompt with Webdriver IO?

I'm working on a CLI with OCLIF. In one of the commands, I need to simulate a couple of clicks on a web page (using the WebdriverIO framework for that). Before you're able to reach the desired page, there is a redirect to a page with a login prompt. When I use WebdriverIO methods related to alerts such as browser.getAlertText(), browser.sendAlertText() or browser.acceptAlert, I always get the error no such alert.
As an alternative, I tried to get the URL when I am on the page that shows the login prompt. With the URL, I wanted to do something like browser.url(https://<username>:<password>#<url>) to circumvent the prompt. However, browser.url() returns chrome-error://chromewebdata/ as URL when I'm on that page. I guess because the focus is on the prompt and that doesn't have an URL. I also don't know the URL before I land on that page. When being redirected, a query string parameter containing a token is added to the URL that I need.
A screenshot of the prompt:
Is it possible to handle this scenario with WebdriverIO? And if so, how?
You are on the right track, probably there are some fine-tunings that you need to address to get it working.
First off, regarding the chrome-error://chromewebdata errors, quoting Chrome DOCs:
If you see errors with a location like chrome-error://chromewebdata/
in the error stack, these errors are not from the extension or from
your app - they are usually a sign that Chrome was not able to load
your app.
When you see these errors, first check whether Chrome was able to load
your app. Does Chrome say "This site can't be reached" or something
similar? You must start your own server to run your app. Double-check
that your server is running, and that the url and port are configured
correctly.
A lot of words that sum up to: Chrome couldn't load the URL you used inside the browser.url() command.
I tried myself on The Internet - Basic Auth page. It worked like a charm.
URL without basic auth credentials:
URL WITH basic auth credentials:
Code used:
it('Bypass HTTP basic auth', () => {
browser.url('https://admin:admin#the-internet.herokuapp.com/basic_auth');
browser.waitForReadyState('complete');
const banner = $('div.example p').getText().trim();
expect(banner).to.equal('Congratulations! You must have the proper credentials.');
});
What I'd do is manually go through each step, trying to emulate the same flow in the script you're using. From history I can tell you, I dealt with some HTTP web-apps that required a refresh after issuing the basic auth browser.url() call.
Another way to tackle this is to make use of some custom browser profiles (Firefox | Chrome) . I know I wrote a tutorial on it somewhere on SO, but I'm too lazy to find it. I reference a similar post here.
Short story, manually complete the basic auth flow (logging in with credentials) in an incognito window (as to isolate the configurations). Open chrome://version/ in another tab of that session and store the contents of the Profile Path. That folder in going to keep all your sessions & preserve cookies and other browser data.
Lastly, in your currentCapabilities, update the browser-specific options to start the sessions with a custom profile, via the '--user-data-dir=/path/to/your/custom/profile. It should look something like this:
'goog:chromeOptions': {
args: [
'--user-data-dir=/Users/iamdanchiv/Desktop/scoped_dir18256_17319',
],
}
Good luck!

Spotify API Token Scope Issue

I have been at this for sometime now and wanted to see if anyone had and idea of what I could be doing wrong. What I am trying to do is add a song to a playlist using the provided Spotify Web APIs. According to the documentation on this https://developer.spotify.com/documentation/web-api/reference/playlists/add-tracks-to-playlist/ I need to establish the scope of the user.
"adding tracks to the current user’s private playlist (including collaborative playlists) requires the playlist-modify-private scope" I have created the playlist as collaborative and I am using the login credentials of my personal account to reach this playlist I created. all this is under the same login.
What I am finding is that my scope is not getting added to my token on my call for my token causes a 403 error when I try to add the song.
Here is what that call looks like
https://accounts.spotify.com/authorize/?client_id=mynumber&response_type=code&scope=playlist-modify-private&redirect_uri=http:%2F%2Flocalhost:55141/Home/GetToken/
here are the docs on using authorization to get the correct token.
https://accounts.spotify.com/authorize/?client_id=894400c20b884591a05a8f2432cca4f0&response_type=code&scope=playlist-modify-private&redirect_uri=http:%2F%2Flocalhost:55141/Home/GetToken/
further more if I go into the dev support here
https://developer.spotify.com/documentation/web-api/reference/playlists/add-tracks-to-playlist/
and click the green try button and then request a new token it works.
Bottom line some how my request is not taking my scope request. Any Ideas?
Thanks
To get the token with a specific scope you need to go to the authorize endpoint and get the code. The code is what you want to get to be able http post to the endpoint https://accounts.spotify.com/api/token and get a token with your desired scopes. You can simply get the code by pasting a url like this in your browser...
https://accounts.spotify.com/authorize?client_id=<client_id>&response_type=code&scope=streaming%20user-read-email%20user-read-private&redirect_uri=<redirect_uri>
Only add %20 in between scopes if you have multiple ones
You will then be sent to spotify's website and they'll verify you want to do this. Once you verify it your browser will redirect you to what you set the redirect_uri to be in the url above. At the end of the url that you are sent to, you should be able to see the parameter name code with the code value assigned to it. You then get that code and put it in your http post body params to the https://accounts.spotify.com/api/token endpoint. Make sure you accurately follow the query params requirements in your post method.
An example of the post in python using the requests library:
authorization = requests.post(
"https://accounts.spotify.com/api/token",
auth=(client_id, client_secret),
data={
"grant_type": "authorization_code",
"code": <code>,
"redirect_uri": <redirect_uri>
},
)
authorization_JSON = authorization.json()
return authorization_JSON["access_token"]
In the end you should get a json that shows the scopes you set a long with a refresh the token later on to make more requests.
I know this answer is quite late but I was experiencing the same issue as well which is how I came across this question. I hope this helps anyone that sees this at a later date.
Source: https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow

Creating new task through WebHook with Asana API

I am working with a form system very similar to WUFOO that allows me to send data to an external website using WebHooks.
I have been able to connect my form to my ASANA system through Zapier but I cannot seem to get the API system to operate correctly. Can someone please advise or assist me on what I am doing incorrectly here?
In the screenshot note the following:
- Web URL functions for any web URL (https or http)
- HTTP method has POST, PUT, or GET options
- Data format allows me to input virtually anything so I can match up form fields with any necessary names for ASANA.
I simply cannot get the system to connect to ASANA. Please help me.
Screen shot of WebHook Options
I don't have access to your exact form builder but assuming it does what it says it is doing you can try the following. I'll use creating a task as an example.
Create a personal access token in Asana. To do this log in to Asana, click the icon in the top right corner and open "My profile settings". Go to the apps tab and create a personal access token. You will only ever see this token once so create a new one if you lose it. Also retrieve your workspace id, you can get it by opening app.asana.com/api/1.0/workspaces while logged in.
Now back to your form. For the website url place the specific endpoint you want to hit at Asana. For example, lets create a new task:
https://app.asana.com/api/1.0/tasks
Under the HTTP Method you want to select POST
Under the HTTP Headers you want to specify something like (replace 0/1234abcd with your access token):
{
"Authorization": "Bearer 0/1234abcd",
"Content-Type": "application/json"
}
You can use Send Raw Data and specify something like the following in the raw data section (replace 1234 with your workspace id):
{
"data": {
"workspace": 1234,
"name": "The name of the task"
}
}
You can of course add other fields- please see the API reference for more information:
https://asana.com/developers/api-reference/tasks
Let me know if that works for you.

Using OAuth dialog for facebook app do not allow to use canvas URL as redirect_uri

I am starting a Facebook app. Following the Getting Started tutorial in the Authorization section, it says I should use this URL to get permission from users:
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_CANVAS_PAGE
I am replacing YOUR_CANVAS_PAGE with my canvas URL, the one I see on my app settings:
https%3A%2F%2Fapps.facebook.com%2F238620302882463%2F
But, then, if I navigate to that page, I get the following error:
An error occurred with Elecciones 2012. Please try again later.
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: Invalid redirect_uri: Given URL is not allowed by the Application configuration.
If I replace YOUR_CANVAS_PAGE with:
http%3A%2F%2Fwww.example.com%2FElecciones2012
The permission dialog works fine. But then I get redirected to my website, not the app inside facebook.com
Any idea why is this happening??
I have seen other apps using a different permission dialogue:
http://www.facebook.com/connect/uiserver.php?app_id=11609831134&method=permissions.request&redirect_uri=http%3A%2F%2Fapps.facebook.com%2Fpetsociety%2F%3Fpf_ref%3Dsb%26ref%3Dts&response_type=none&display=page&perms=email%2Cpublish_actions&auth_referral=1
But it looks it is part of another set of APIs.
I got the same problem too. Looks like the problem is in "Canvas URL". You cannot use your app id in canvas URL like:
"https%3A%2F%2Fapps.facebook.com%2F238620302882463%2F"
Instead, the namespace should be used as your canvas URL. for example:
"https://apps.facebook.com/myapplication/"
You can set your app namespace in the application settings in facebook.

Resources