Unable to get auth token from twitter - twitter

I am trying to get auth token from twitter api https://api.twitter.com/oauth2/token but getting 403 forbidden issue.
My credentials(API Key and API Secret key) are right and verified.
I tried that on postman by converting online my credentials in base64.
this.twitterTokenURL = "https://api.twitter.com/oauth2/token";
var combined = encodeURIComponent(this.consumerKey) + ":" + encodeURIComponent(this.consumerSecret);
base64Encoded = btoa(combined);
// Get the token
this.http.post(this.twitterTokenURL, { 'Authorization': 'Basic ' + base64Encoded, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }, "grant_type=client_credentials").
map(res => res.json()).subscribe((data) => {
this.authorization = data;
console.log(data);
if (data && data.token_type && data.token_type === "bearer") {
//resolve(data)
}
resolve(this.data);
})

Related

The view function did not return a valid response. The return type must be a string, dict

using Spotify API and Flask I am trying to extend refresh_token validity. As a result, when I send a request to the server, I get this error:
*The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a Response.*
My code:
#app.route("/index")
def index():
if time.time() > session['expires_in']:
payload = session['refresh_token']
ref_payload = {
'grant_type': 'refresh_token',
'refresh_token':session["refresh_token"]
}
header={'Authorization': 'Basic ' + '<CLIENT_ID>:<CLIENT_SECRET'}
r = requests.post(AUTH_URL, data=ref_payload, headers=header)
return r
#app.route("/q")
def api_callback():
session.clear()
code = request.args.get('code')
res = requests.post(AUTH_URL, data={
"grant_type":"authorization_code",
"code":code,
"redirect_uri":REDIRECT_URI,
"client_id":CLIENT_ID,
"client_secret":CLIENT_SECRET
})
res_body = res.json()
session["token"] = res_body.get("access_token")#token
session["expires_in"] = res_body.get("expires_in")#time
session["refresh_token"] = res_body.get("refresh_token")#reflesh token
return redirect("index")
https://accounts.spotify.com/api/token is accepted as AUTH_URL
Most likely the problem is very commonplace, but I can't think of a solution now. Thanks in advance
I solved this problem. In my configurashion file i was create a veriable in which i encode my client_id and client_secret to base64 format:
ID_SEC = CLIENT_ID +':'+ CLIENT_SECRET
base64_encode = base64.b64encode(ID_SEC.encode()).decode()
After in the header i edit authorisation :
header={
'Content-Type':'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': 'Basic {}'.format(base64_encode)
}
And send post requests:
r = requests.post(AUTH_URL, data=ref_payload, headers=header)

Login authentication using token error Access-Control-Allow-Origin'

userAuthentication(userName, password) {
let headers = new Headers();
var data = "username=" + userName + "&password=" + password + "&grant_type=password";
// var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });
headers.append('Content-Type', 'application/x-www-urlencoded');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('No-Auth','True');
headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT');
return this.http.post(environment.apiUrl + 'token', data, { headers: headers })
.pipe(map(data => data.json()),
catchError((error: any) => {
throw error;
}));
}
}
I am using angular on client side and asp.net mvc on server side.I an facing an error Access-Control-Allow-Origin
The Error you got is because you don't have required permissions to access API
add this line inside your API code
you have to install cors first
Install-Package Microsoft.AspNet.WebApi.Cors
after add this line inside your API
config.EnableCors();
"config" refers to httpconfiguration class
you will now able to access your API

twitter login - xlm version =1.0 encoding = "UTF-8" error 415 Callback URL not approved for this client application

I am trying to use a social auth (twitter into firebase) on android and I get the error above .
As I understand it there is nothing wrong with my code , just some error in twitter developer platform, I ll post both of them just to be sure
_twitterSignIn = async () => {
context = this
const twitterAccessToken = await getTwitterAccessToken();
const twitterAccessTokenSecret = await getTwitterAccessTokenSecret();
console.log("twitterAccessToken: " + twitterAccessToken + ", twitterAccessTokenSecret: " + twitterAccessTokenSecret);
auth({ consumerKey: Constants.TWITTER_COMSUMER_KEY, consumerSecret: Constants.TWITTER_CONSUMER_SECRET, accessToken: twitterAccessToken, accessTokenSecret: twitterAccessTokenSecret }
, "myapp://twitter", { accessType: "write", forSignIn: false, forceLogin: false, screenName: '' }).then(({ accessToken, accessTokenSecret, id, name }) => {
// context.loginLoader({loading:false})
context.props.updateLoader({ loading: false })
AsyncStorage.setItem(TWITTER_AUTH_TOKEN, accessToken)
AsyncStorage.setItem(TWITTER_AUTH_TOKEN_SECRET, accessTokenSecret)
setTwitterConfig();
}).catch(console.error);
}
PS: I also tryed adding twittersdk:// to callback url ,still doesnt work

Search for Twitter handles using Google Apps Script and Twitter API - doesn't work

I'm trying to find Twitter handles from a spreadsheet containing names of people.
I can't get it work with this request, which I believe is the one I should be using as I only have peoples names (e.g. Adam Smith): api.twitter.com/1.1/users/search.json?q=
I get the following error:
Request failed for api.twitter.com/1.1/users/search.json?q=Name returned code 403. Truncated server response: {"errors":[{"message":"Your credentials do not allow access to this resource","code":220}]} (use muteHttpExceptions option to examine full response) (line 38).'
I've tried searching this error but that hasn't helped me so far.
If I use, for example, this request, it works: api.twitter.com/1.1/users/show.json?screen_name=
So I can get the screen_name back in the spreadsheet, but that's pointless obviously because it needs the screen name to work in the first place...
The whole thing is based on this work, all the requests in that code work for me. It's just this search request that doesn't work. What's going wrong?
var CONSUMER_KEY = 'x';
var CONSUMER_SECRET = 'x';
function getTwitterHandles(name) {
// Encode consumer key and secret
var tokenUrl = "https://api.twitter.com/oauth2/token";
var tokenCredential = Utilities.base64EncodeWebSafe(
CONSUMER_KEY + ":" + CONSUMER_SECRET);
// Obtain a bearer token with HTTP POST request
var tokenOptions = {
headers : {
Authorization: "Basic " + tokenCredential,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
method: "post",
payload: "grant_type=client_credentials"
};
var responseToken = UrlFetchApp.fetch(tokenUrl, tokenOptions);
var parsedToken = JSON.parse(responseToken);
var token = parsedToken.access_token;
// Authenticate Twitter API requests with the bearer token
var apiUrl = 'https://api.twitter.com/1.1/users/search.json?q=screen_name='+name;
var apiOptions = {
headers : {
Authorization: 'Bearer ' + token
},
"method" : "get"
};
var responseApi = UrlFetchApp.fetch(apiUrl, apiOptions);
var result = "";
if (responseApi.getResponseCode() == 200) {
// Parse the JSON encoded Twitter API response
var tweets = JSON.parse(responseApi.getContentText());
return tweets.id
}
Logger.log(result);
}
Edit: deleted the https a few times because of the URL limit
You can not search for users using application-only authentication (bearer token). See https://dev.twitter.com/oauth/application-only. A user context (access token) is needed for that request. You can get your own access token from https://apps.twitter.com.

Venmo Oauth 2.0 Using Ionic Framework - 400 Bad Request Error

I am currently trying to login to my app that is built on Ionic Framework using Venmo's Oauth API. I am attempting to use the Server Side Flow so that I can have a longer term access token. I am able to receive a code and set it to a requestToken variable.
However, when I attempt to post to "https://api.venmo.com/v1/oauth/access_token" with my Client Id, Client Secret, and Request Token, I get the following error alert: "ERROR: [object Object]".
In checking my console, I see that the error is a 400 Bad Request error coming on my post request, although it does appear that I have a valid request token. The error message is as follows: "Failed to load resource: the server responded with a status of 400 (Bad Request)".
Below is the code of the login function I am using to login via Venmo's Oauth API:
//VENMO SERVER SIDE API FUNCTION
var requestToken = "";
var accessToken = "";
var clientId = "CLIENT_ID_HERE";
var clientSecret = "CLIENT_SECRET_HERE";
$scope.login = function() {
var ref = window.open('https://api.venmo.com/v1/oauth/authorize?client_id=' + clientId + '&scope=make_payments%20access_profile%20access_friends&response_type=code');
ref.addEventListener('loadstart', function(event) {
if ((event.url).startsWith("http://localhost/callback")) {
requestToken = (event.url).split("?code=")[1];
console.log("Request Token = " + requestToken);
$http({
method: "post",
url: "https://api.venmo.com/v1/oauth/access_token",
data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + requestToken
})
.success(function(data) {
accessToken = data.access_token;
$location.path("/make-bet");
})
.error(function(data, status) {
alert("ERROR: " + data);
});
ref.close();
}
});
}
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function(str) {
return this.indexOf(str) == 0;
};
}
This function is from this helpful walkthrough article by Nic Raboy (https://blog.nraboy.com/2014/07/using-oauth-2-0-service-ionicframework/). I think that the problem may be in how I am presenting the data array, so if anyone has any experience in successfully implementing a Venmo API in Ionic, your help would be much appreciated!
I was actually able to solve this issue with the method described above. In my original code, I omitted the line used to set the content type to URL encoded (which was included in Nic's example). Once I added this line, the request functioned as expected. The line was as follows:
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Resources