Not able to hit Twitter API through POSTMAN - twitter

I was trying to hit Twitter API to retrieve data from POSTMAN but I am stuck at an error.
I have created a project in Twitter and then created an app which is associated with the twitter project. Retrieved the Key, Secret and Bearer Token. I hit the below endpoint with Bearer token and got the error
endpoint : https://api.twitter.com/2/tweets?ids=1261326399320715264,1278347468690915330
Error: When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.
Then I hot the same endpoint using OAuth 1.0 with Consumer Key, Consumer Secret, Access Token and Access Secret and getting the below error
{
"title": "Unauthorized",
"type": "about:blank",
"status": 401,
"detail": "Unauthorized"
}
I do not understand what I am missing there. Can someone please help with this?
Edit by Espoir Murhabazi: I have tried to use beared token to authenticate as shown in this example but in vain
I tried to use the authentication scheme used by tweepy but also in vain. I look like there is something we are missing.
Here is a full example of what I have tried:
import requests
import os
import sys
from tweepy import OAuthHandler
from dotenv import load_dotenv
load_dotenv()
def get_twitter_auth():
"""Setup Twitter authentication.
Return: tweepy.OAuthHandler object
"""
try:
consumer_key = os.getenv('TWITTER_CONSUMER_KEY')
consumer_secret = os.getenv('TWITTER_CONSUMER_SECRET')
access_token = os.getenv('TWITTER_ACCESS_TOKEN')
access_secret = os.getenv('TWITTER_ACCESS_SECRET')
assert all([consumer_key, access_secret, access_token, consumer_secret])
except KeyError:
sys.stderr.write("TWITTER_* not found\n")
sys.exit(1)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
return auth.apply_auth()
protected_url = "https://ads-api.twitter.com/9/insights/keywords/search?granularity=HOUR&keywords=developers&start_time=2021-07-02T10:00:00Z"
oauth = get_twitter_auth()
response = requests.get(url=protected_url, auth=oauth)
print(response.content, 10 * "**=|")
Thanks

Add your bearer token(received from twitter developer account) in the Authorization tab of postman[see attached image] and then request. I was able to get response for endpoint you mention.

Goto :
https://developer.twitter.com/en/portal/projects/new
Create a new app , and copy the bearer token that will be generated
and in postman use :
output:

First make sure you are using GET request instead of the other request type for this specific request (as shown in their docs here with a Postman example. I just tried to use POST and I got the same error, but works fine on GET request. This is the result I get with the URL in the question copied and pasted without any edits; and using GET request with Bearer Token as my authentication:
{
"data": [
{
"id": "1261326399320715264",
"text": "Tune in to the #MongoDB #Twitch stream featuring our very own #suhemparack to learn about Twitter Developer Labs - starting now! https://twitter.com/MongoDB/status/1261091720801980419"
},
{
"id": "1278347468690915330",
"text": "Good news and bad news: \n\n2020 is half over"
}
]
}
url in the above snippet was edited and replaced with the full URL as StackOverflow doesn't accept shortened URLs.
To change the request type do the following:
Open Postman
Click on the select input (also called combo box) on the left side of the URL input textbox (where you wrote the URL https://api.twitter.com/2/tweets?ids=1261326399320715264,1278347468690915330). Shouldn't be hard to see.
Select GET on the options. If that doesn't work then it's time to reset your keys.
To reset your keys (called regenerating according to Twitter) do the following (you may skip this whole process if the above solved your issue):
go to your project in your Twitter developer account.
In the main view for your project you should see your apps with two icons; a gear and key icon. Look for the app you want to edit, click on the key icon next to it
On the next page you can regenerate any of the keys you might have lost access to. If you choose to regenerate the Bearer Token, click on regenerate on the same line with the Bearer Token text.
You can now copy the Bearer Token to your clipboard, I recommend copying it to somewhere safe so you don't have to keep resetting.
After copying the Bearer Token, open postman
Duplicate the tab with the GET request
Under the URL textbox there should be a tab written Authorisation. Click on it.
Under that tab there should be a select input (combobox) with the label type, click on it and select Bearer Token.
On the right there will appear an input with the label token on its left side. Go to that input and paste your URL, use the same exact one you used in the question as it works as is.
For the final step, press Enter or go to the button written Send on the right side of the URL textbox. If everything was done correctly you should have your results.

Bearer Tokens are the predominant type of access token used with OAuth 2.0. A Bearer Token is an opaque string, not intended to have any meaning to clients using it. Instead of using a bearer token try with the access_token and access_token_secret. For more info refer this

Related

Using Postman to test KOHA RestAPI but keep getting authentication failure

I have a problem working with Postman and Koha RestAPI to display desired input.
I want to try GET request on Postman using this URL as endpoint: https://{KOHADomain}/api/v1/patrons?userid={userid}.
What supposed to happen is the output should display all patrons detail in json or xml, but I keep getting this message:
{
"error": "Authentication failure."
}
The url works fine in the browser after login using KOHA privilege account. It displays all the desired output in xml form, but not in Postman.
The methods that I have tried:
Clear browser's cache.
Re-login Koha account.
Use Basic Auth.
Use OAuth 2.0. (client_id, secret_key, Token Access URL)
I really appreciate if someone could help me find the solution for this problem.

Issue with invalid_grant error with Google Oauth2

Cheers everybody,
we have been deeply reading google documentation on exchanging access_token from google in order our (delphi)desktop application to SSO with google from server side. Here is the payload we send first look like:
https://accounts.google.com/o/oauth2/v2/auth?client_id=1000217514248-t1lojs6f8ed7l9ocrpbm98leahtum8n1.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&state=E1DF2FBA-0A66-4D69-B594-5EB8F7828AF7&scope=openid+profile&include_granted_scopes=true&code_challenge=C832DA50-E55A-499D-89B8-493BB4123C94&login_hint=test#Speelkriebel.be
Normally after this it redirects me to login in to our test user and after this according to the documentation we send a POST request to the end point token in order to get the access_token and refresh_token...: 'https://oauth2.googleapis.com/token
with the following parameters, the 'code' is generated we also send it as follow:
client_id=1000217514248-t1lojs6f8ed7l9ocrpbm98leahtum8n1.apps.googleusercontent.com
grant_type=authorization_code
client_secret=******
code= 4/1AY0e-g4GlavO38PI5Oo3vq04Pc4lMWN77et-02UiVWOsT-IyRQnU1lq19qo
redirect_uri = urn:ietf:wg:oauth:2.0:oob
The response is always
{
"error_description": "Missing code verifier.",
"error": "invalid_grant"
}
We have tried to send the client secret id also, Does it have to do with our code_challenge ? are the end points url and initial url okay? What are we missing? We are using CEF4Delphi as "browser like experience in order for the user to type in their google credentials. We have been reading this: https://developers.google.com/identity/protocols/oauth2/web-server#offline
We were also trying the playground :https://developers.google.com/oauthplayground/
we were sending the initial url in a chrome which generated a "code" and in the playground we inserted the code, and still got the same error of missing code verifier.
Thanks Guys
You seam to have URL encoded a lot of the values try not doing that. Also try using the basic call, before you start adding everything else. It should help you figure out which one of those extra parameters you are sending that's causing your issues.
https://accounts.google.com/o/oauth2/auth?client_id={clientid}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=profile&response_type=code
Also make sure that the client id is from an installed / other type client
This may also help Google 3 Legged OAuth2 Flow
For installed apps, the code challenge and verifier are parameters for enhancing the security of the OAuth flow through PKCE [1].
There is additional documentation about generating a code challenge and verifier here [2].
[1] https://www.rfc-editor.org/rfc/rfc7636
[2] https://developers.google.com/identity/protocols/oauth2/native-app#step1-code-verifier

How do I Implement twitter Oauth into my Google chrome extension

I figured out how to get the sign in button and redirect through php code. BUT, Chrome Dev only allows client side code. How do I get the log in with twitter with client side code for my Chrome app?
is there a way to run php code for a chrome app?
Here is another alternative to CodeBird for authenticating a twitter user in a Chrome extension.
The key with this approach is to provide Twitter with a legitimate domain for the callback URL for your app. Then, use content scripts to inject a script onto that same domain. That script will parse the query string of the URL to get the tokens and send those tokens in a message to your extension's background script. Your background script will take the tokens and then perform the third leg of the oauth process, which will finally get you the oauth token and oauth token secret.
Here is a brief example:
in your manifest.json, make sure your content script matches the same domain that you put in your twitter app settings callback URL:
"content_scripts": [{
"matches": ["https://andyjiang.com/*"],
"js": ["js/session.js"]
}]
Then, in your js/session.js file, have this sort of logic:
chrome.runtime.sendMessage({type: 'auth', session:
window.location.search.substr(1)}, function(response) {
window.open('', '_self', '');
window.close();
});
In your background script, have some logic that listens for the message, gets the token, and uses Twitter's API for the third leg of the oauth process to finally get the oauth token and oauth token secret, which you can then save in localStorage or chrome.storage.
Here is sample code of the logic:
https://github.com/lambtron/chrome-extension-twitter-oauth-example
Hope that helps!
You can use the Chrome Identity API for this. Check out Non-Google account authentication for simple instructions on making a request using the launchWebAuthFlow API function.
Previously, there were client side libraries for implementing the OAuth flow, such as oauth2-extensions described here, but thankfully this is not required anymore .
Update
I've been playing around trying to get an example working for Twitter, but haven't quite got there. It appears that Twitter doesn't have an API endpoint that matches the OAuth2 URL that is expected. I think in the case of Twitter, you may have to use OAuth 1.0a instead, which would require a library after all. I found one called CodeBird. I will try and investigate further though.
Example using Chrome Identity API to Authorise Instagram
You need to register the client to your provider with https://abcdefghijklmnopqrstuvwxyzabcdef.chromiumapp.org/intagram_cb, where 'abcdefghijklmnopqrstuvwxyzabcdef' is replaced with your extension ID and intagram_cb is name for a path to be able to distinguish between other providers you wish to authenticate with within the extension. If you only have one, then you can omit it.
Add provider to the permissions property in the manifest.json file:
"permissions": [
"*://*.instagram.com/*"
]
Get access token. You obtain the client_id token from your provider account:
var redirect_uri = chrome.identity.getRedirectURL("intagram_cb");
var client_id = "123456789012345";
var auth_url = "https://instagram.com/oauth/authorize/?" +
"client_id=" + client_id + "&" +
"response_type=token&" +
"redirect_uri=" + encodeURIComponent(redirect_uri);
chrome.identity.launchWebAuthFlow({'url':auth_url, 'interactive': true},
function(redirect_url) {
// extract the token from this url and use it for future requests
var accessToken = redirect_url.substring(redirect_url.indexOf("=") + 1);
}
});

Using Postman to access OAuth 2.0 Google APIs

I am trying to access Proximity Google API using Postman chrome app. I have followed tutorials on postman and google dev website but I'm still getting 401 error message.
What am I doing?
Step 1 - Enable Proximity API:
In order to use Proximity API, it has to be first enabled in Google Dev console.
Using this tutorial I have enabled support for Proximity API for my project
Step 2 - Get the credentials:
According to this tutorial, I need to get client ID and secret. This is where I am confused. Credentials->Add credentials->OAuth2.0 client ID->select Chrome App radio button (since I am using Postman)->enter last part of Postman's Chrome Web store URL [which is fhbjgbiflinjbdggehcddcbncdddomop]->hit create button These steps will only generate a client ID, not a secret..am I doing something wrong?
From the Google Dev console, one can download an JSON file which has client id, auth URI and Token URI
I downloaded this but this is of little help if I am using Postman. I am guessing this JSON file is something that can be included in a JS application.
Step 3 - Use Postman to test the API
What am I getting?
And, once I click on the debug URL, I see the following screen
Postman will query Google API impersonating a Web Application
Generate an OAuth 2.0 token:
Ensure that the Google APIs are enabled
Create an OAuth 2.0 client ID
Go to Google Console -> API -> OAuth consent screen
Add getpostman.com to the Authorized domains. Click Save.
Go to Google Console -> API -> Credentials
Click 'Create credentials' -> OAuth client ID -> Web application
Name: 'getpostman'
Authorized redirect URIs: https://www.getpostman.com/oauth2/callback
Copy the generated Client ID and Client secret fields for later use
In Postman select Authorization tab and select "OAuth 2.0" type. Click 'Get New Access Token'
Fill the GET NEW ACCESS TOKEN form as following
Token Name: 'Google OAuth getpostman'
Grant Type: 'Authorization Code'
Callback URL: https://www.getpostman.com/oauth2/callback
Auth URL: https://accounts.google.com/o/oauth2/auth
Access Token URL: https://accounts.google.com/o/oauth2/token
Client ID: Client ID generated in the step 2 (e.g., '123456789012-abracadabra1234546789blablabla12.apps.googleusercontent.com')
Client Secret: Client secret generated in the step 2 (e.g., 'ABRACADABRAus1ZMGHvq9R-L')
Scope: see the Google docs for the required OAuth scope (e.g., https://www.googleapis.com/auth/cloud-platform)
State: Empty
Client Authentication: "Send as Basic Auth header"
Click 'Request Token' and 'Use Token'
Set the method, parameters, and body of your request according to the Google docs
The best way I found so far is to go to the Oauth playground here: https://developers.google.com/oauthplayground/
Select the relevant google api category, and then select the scope inside that category in the UI.
Get the authorization code by clicking "authorize API" blue button.
Exchange authorization code for token by clicking the blue button.
Store the OAuth2 token and use it as shown below.
In the HTTP header for the REST API request, add: "Authorization: Bearer ". Here, Authorization is the key, and "Bearer ". For example: "Authorization: Bearer za29.KluqA3vRtZChWfJDabcdefghijklmnopqrstuvwxyz6nAZ0y6ElzDT3yH3MT5"
The current answer is outdated. Here's the up-to-date flow:
The approach outlined here still works (28th of july 2022, confirmed by Jordy)
We will use the YouTube Data API for our example. Make changes accordingly.
Make sure you have enabled your desired API for your project.
Create the OAuth 2.0 Client
Visit https://console.cloud.google.com/apis/credentials
Click on CREATE CREDENTIALS
Select OAuth client ID
For Application Type choose Web Application
Add a name
Add following URI for Authorized redirect URIs
https://oauth.pstmn.io/v1/callback
Click Save
Click on the OAuth client you just generated
In the Topbar click on DOWNLOAD JSON and save the file somewhere on your machine.
We will use the file later to authenticate Postman.
Authorize Postman via OAuth 2.0 Client
In the Auth tab under TYPE choose OAuth 2.0
For values under Configuration Options enter the values found inside the client_secret_[YourClientID].json file we downloaded in step 9
Click on Get New Access Token
Make sure your settings are as follows:
Click here to see the settings
(In addition, multiple scope can be as follows, space-delimited: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile")
Click on Request Token
A new browser tab/window will open
Once the browser tab opens, login via the appropriate Google account
Accept the consent screen
Done
Ignore the browser message "Not safe" etc. This will be shown until your app has been screened by Google officials. In this case it will always be shown since Postman is the app.
go to https://console.developers.google.com/apis/credentials
create web application credentials.
Postman API Access
use these settings with oauth2 in Postman:
Auth URL = https://accounts.google.com/o/oauth2/auth
Access Token URL = https://accounts.google.com/o/oauth2/token
Choose Scope for the HTTP API
Generate Token
to add Schema use:
SCOPE = https: //www.googleapis.com/auth/admin.directory.userschema
post https: //www.googleapis.com/admin/directory/v1/customer/customer-id/schemas
{
"fields": [
{
"fieldName": "role",
"fieldType": "STRING",
"multiValued": true,
"readAccessType": "ADMINS_AND_SELF"
}
],
"schemaName": "SAML"
}
to patch user use:
SCOPE = https://www.googleapis.com/auth/admin.directory.user
PATCH https://www.googleapis.com/admin/directory/v1/users/admin#email.com
{
"customSchemas": {
"SAML": {
"role": [
{
"value": "arn:aws:iam::123456789123:role/Admin,arn:aws:iam::123456789123:saml-provider/GoogleApps",
"customType": "Admin"
}
]
}
}
}
I figured out that I was not generating Credentials for the right app type.
If you're using Postman to test Google oAuth 2 APIs, select
Credentials -> Add credentials -> OAuth2.0 client ID -> Web Application.
This is an old question, but it has no chosen answer, and I just solved this problem myself. Here's my solution:
Make sure you are set up to work with your Google API in the first place. See Google's list of prerequisites. I was working with Google My Business, so I also went through it's Get Started process.
In the OAuth 2.0 playground, Step 1 requires you to select which API you want to authenticate. Select or input as applicable for your case (in my case for Google My Business, I had to input https://www.googleapis.com/auth/plus.business.manage into the "Input your own scopes" input field). Note: this is the same as what's described in step 6 of the "Make a simple HTTP request" section of the Get Started guide.
Assuming successful authentication, you should get an "Access token" returned in the "Step 1's result" step in the OAuth playground. Copy this token to your clipboard.
Open Postman and open whichever collection you want as necessary.
In Postman, make sure "GET" is selected as the request type, and click on the "Authorization" tab below the request type drop-down.
In the Authorization "TYPE" dropdown menu, select "Bearer Token"
Paste your previously copied "Access Token" which you copied from the OAuth playground into the "Token" field which displays in Postman.
Almost there! To test if things work, put https://mybusiness.googleapis.com/v4/accounts/ into the main URL input bar in Postman and click the send button. You should get a JSON list of accounts back in the response that looks something like the following:
{
"accounts": [
{
"name": "accounts/REDACTED",
"accountName": "REDACTED",
"type": "PERSONAL",
"state": {
"status": "UNVERIFIED"
}
},
{
"name": "accounts/REDACTED",
"accountName": "REDACTED",
"type": "LOCATION_GROUP",
"role": "OWNER",
"state": {
"status": "UNVERIFIED"
},
"permissionLevel": "OWNER_LEVEL"
}
]
}
Google has changed the Access Token URL: https://accounts.google.com/o/oauth2/token.
It now needs to be: https://oauth2.googleapis.com/token
As an addition to the top answer by #DimaTx, don't forget to put checkmark on the "authorize using browser" tickbox, as explained by team postman themselves in github.com/postmanlabs/postman-app-support/issues/7700
This will prevent/solve the “This browser or app may not be secure” result.

How to renew access token secret for Intuit QuickBooks integration with .net application?

I am using code in following link to Renew access token for Intuit QuickBooks integration.
https://gist.github.com/IntuitDeveloperRelations/7259345
but, I am unable to test this code as intuit renew its access token only after 150 days from token creation date and I've created token only few days back. So I don't know the output. Right now, it is generating xml response with error message.
Now this method is returning me a single string which seems to be the Access Token. Do I also need to renew Access Token Secret ? If yes, then how to generate it ? Or the output contains secret as well ?
Actually, Can you give me the output for this method?
A successful response looks like this:
<ReconnectResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://platform.intuit.com/api/v1">
<ErrorMessage/>
<ErrorCode>0</ErrorCode>
<ServerTime>2012-01-04T19:21:21.0782072Z</ServerTime>
<OAuthToken>qye2eIdQ5H5yMyrlJflUWh712xfFXjyNnW1MfbC0rz04TfCP</OAuthToken>
<OAuthTokenSecret>cyDeUNQTkFzoR0KkDn7viN6uLQxWTobeEUKW7I79</OAuthTokenSecret>
</ReconnectResponse>
Refer to Intuit's documentation.
Notice that you will get back both a new token and a new token secret which you should store.
Remember that you can use Intuit's OAuth Playground to generate shorter lived tokens to test with.
You can test Reconnect API in the following way-
1. Navigate to IPP Playground- Go to Manage My Apps->Click on your app
Fill in consumer key and consumer secret in links below.
Prod: https://appcenter.intuit.com/Playground/OAuth/IA/?ck=prodConsumerKey&cs=prodConsumerSecret
Alternatively, you can navigate to the Manage page for your app on stage or prod and click ‘Test connect to app (OAuth)’.
Enter the duration you would like for the issued OAuth tokens (e.g., 3600 for successful Reconnect) in the ‘Access Token Duration’ field.
Click on the Connect to QuickBooks button, go through OAuth flow to authorize a connection to a realm.
Under the resulting Post-Connection Interactions heading, click ‘Reconnect API Test’. Screen shot attached.
A new page will launch where your OAuth tokens are displayed. Copy these values to your application to test Reconnect.
See if this reconnection code sample helps:
http://developer.qbapi.com/Reconnect-to-Quickbooks-Online-.aspx

Resources