Twitter integration using oAuth error - twitter

Hello
I have tried to post a tweet from my application. When I press on the button "post tweet" the authentication window (login window by twitter) opens, but when it is loaded my application just exits.
The following error occurs in the log;
[ERROR] Error Domain=com.google.GDataXML Code=-1 "The operation couldn’t be completed. (com.google.GDataXML error -1.)". in -[TiDOMDocumentProxy parseString:] (TiDOMDocumentProxy.m:50)
And in the end it says
terminate called after throwing an instance of 'NSException
The code I used is:
var oAuthAdapter = new OAuthAdapter('SECRET KEY', 'KEY', 'HMAC-SHA1');
// load the access token for the service (if previously saved)
oAuthAdapter.loadAccessToken('twitter');
oAuthAdapter.loadAccessToken('twitter');
oAuthAdapter.send('https://api.twitter.com/1/statuses/update.json', [['status', 'Tweet from appcelerator ' + Math.random()]], 'Twitter', 'Published.', 'Not published.');
if (oAuthAdapter.isAuthorized() == false) {
// this function will be called as soon as the application is authorized
var receivePin = function(){
// get the access token with the provided pin/oauth_verifier
oAuthAdapter.getAccessToken('https://api.twitter.com/oauth/access_token');
// save the access token
oAuthAdapter.saveAccessToken('twitter');
};
// show the authorization UI and call back the receive PIN function
oAuthAdapter.showAuthorizeUI('https://api.twitter.com/oauth/authorize' +
oAuthAdapter.getRequestToken('https://api.twitter.com/oauth/request_token'), receivePin);
}

Found the answer.
The line
oAuthAdapter.showAuthorizeUI('https://api.twitter.com/oauth/authorize'
Should be
oAuthAdapter.showAuthorizeUI('https://api.twitter.com/oauth/authorize?'

Use This code instead of above two lines of showAuthorization and getRequestToken
oAuthAdapter.showAuthorizeUI('https://twitter.com/oauth/authorize?oauth_token=' +
oAuthAdapter.getRequestToken('https://twitter.com/oauth/request_token',
[['oauth_callback', 'oob']]), receivePin, PinFinder.twitter);

Related

Protect API can be accessed by Ajex without Login to Active Directory

I followed this example (https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-protect-backend-with-aad) and selected "OAuth 2.0" under "Setting > User authorization" for the Echo API.
Then, I created an html file with and trigger an ajax call to the Echo API "https://{myapi}.azure-api.net/echo/resource-cached?param1=sample"
I assume that I should received an error something like access denied or no authorization because this API is supposed to be protected by my OAuth Server (according to the example, it is my AD). However, this ajax call return Status code : 200. I don't need to login my AD but can consume the API.
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: "https://{myapi}.azure-api.net/echo/resource?param1=sample"
,headers: {
'Cache-Control':'no-cache',
'Ocp-Apim-Trace':'true',
'Ocp-Apim-Subscription-Key':'xxxxxxxxxxxxxxxxxxxxxx'
}
,success: function(result){
$("#div1").html(JSON.stringify(result));
}
,error : function(result) {
alert(JSON.stringify(result));
}
});
});
});
I have created another API named "demo" manually with mock response. This API returns an json {'sampleField' : 'test'}. My Ajex call receives the json without issu even I have applied "OAuth 2.0" as "User Authorization" in that API.
Is there anything I missed or I misunderstood how it works?
Finally, JWT is required to block it.

Refresh token must be passed in or set as part of setAccessToken Youtube API

I have the following code
if (file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$newAccessToken = $client->getAccessToken();
$accessToken = array_merge($accessToken, $newAccessToken);
file_put_contents($credentialsPath, json_encode($accessToken));
}
}
But after an hour, if I try to use Youtube Data API, I am getting the following error,
Fatal error: Uncaught exception 'LogicException' with message 'refresh token must be passed in or set as part of setAccessToken' in /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/vendor/google/apiclient/src/Google/Client.php:267 Stack trace: #0 /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/youtube.php(26): Google_Client->fetchAccessTokenWithRefreshToken(NULL) #1 /var/sentora/hostdata/zadmin/public_html/channel/apiwrap.php(3): require_once('/var/sentora/ho...') #2 {main} thrown in /var/sentora/hostdata/zadmin/public_html/classes/library/youtube/vendor/google/apiclient/src/Google/Client.php on line 267
Please help.
You need to set these 2 things. The refresh token is not returned because we didn't force the approvalPrompt. The offline mode is not enough. We must force the approvalPrompt. Also, the redirect URI must be set before these two options. It worked for me.
$client = new Google_Client();
$client->setApplicationName('Project Name');
$client->setScopes('SCOPES');
$client->setAuthConfig('JSON_FILE_PATH');
$client->setRedirectUri($this->redirectUri);
$client->setAccessType('offline'); //this line is magic point
$client->setApprovalPrompt('force'); //this line is magic point
This is worked for me. i am able to get new token using refresh token.

OAuth 2.0 access token has expired, and a refresh token is not available

I have a web based application which use Google OAuth2.0 as the login framework. It works nicely previously until yesterday. The applcation couldn't get the refresh token after the access token expired. Besides that, the "Request for permission" page had change to "Have offline access" instead of "Know who you are on Google" and "View you email"
Originally, the "Request for permission" page will request the access to "Know who you are on Google" and "View you email". After user logout and attempts second login, the "Request for permission" page will be the same too.
However, until yesterday, the "Request for permission" page changed to "Have offline access". After the access token is expired, I got the error messsage below:
PHP Fatal error: Uncaught exception 'Google_AuthException' with message 'The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.' in /home2/xxxx/public_html/test/google-api-php-client/src/auth/Google_OAuth2.php:221
I tried $client->setAccessType('online'); . However, I still got this fatal error with me. Below is my code to get the access token :
if ($client->getAccessToken()) {
$token = $client->getAccessToken();
$authObj = json_decode($token);
$refreshToken = $authObj->refresh_token;
$user = $oauth2->userinfo->get();
$me = $plus->people->get('me');
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
I tried to search for similar problem like me but I couldn't find one. This happened since yesterday. Before this, I never made any change on the codes.
With his comments, Fabian Parzefall helped me getting this fixed.
Here's my script :
if($client->isAccessTokenExpired()) {
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
}
It's actually pretty simple. Instead of asking him to click the "connect me" button (as put by the demo script provided by the GA API team), I redirect him directly.
Not sure if it's the proper/safer way, but that's the one working for me right now!
if($client->isAccessTokenExpired()) {
$client->authenticate();
$NewAccessToken = json_decode($client->getAccessToken());
$client->refreshToken($NewAccessToken->refresh_token);
}
The answer above is 'correct' but I faffed around working out where to put it(!)... so post this for any one else trying out examples that end up with tokens expiring(!).
Once your code has done whatever token stuff it needs, and your client has an access token... then check it is still valid and if not send off for reauthorisation!
// Stuff to do with getting tokens and storing in session etc...
if ($client->getAccessToken()) { // Hey! we got one!
if($client->isAccessTokenExpired()) { // Oh! its not good - go for another
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
exit();
}
try{
...
}

can't get access token using refresh token

I wrote desktop application on java, which have access to the Google drive. (it just uploads and downloads files).
At the moment access type is online. when I need to access files/folders to the drive, I
redirect he browser to a Google URL and get access code:
String code = "code that was returned from brouser"
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
everything works well! but I need to have that redirection only first time.
When I google, in the Google Drive API documentation I found that I can get refresh token via browser redirection and save it on DB for instance. (In the other word, I can use offline access).
And every time when I need to read data from google drive, I get access token using refresh token without redirection. is not it?
so I get refresh token like that:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=695230079990.apps.googleusercontent.com&scope=https://www.googleapis.com/auth/drive&response_type=code&redirect_uri=https://localhost
question 1
I get code, from the browser redirecting. it's refresh token, is not it?
now, I need to get access token using that refresh token.
$.ajax({
type: "POST",
url: 'https://accounts.google.com/o/oauth2/token',
data: {
client_id: "695230079990.apps.googleusercontent.com",
client_secret: 'OWasYmp7YQ...4GJaPjP902R',
refresh_toke: '4/hBr......................xwJCgQI',
grant_type: 'refresh_token'
},
success: function(response) {
alert(response);
}
});
but I have error 400;
question 2) when I try to change redirect url I have that error: *
Invalid parameter value for redirect_uri: Non-public domains not allowed: https://sampl.ecom
so, must I create web applications Client ID , instead of installed application from google APIs console? Can't I change Redirect URI in installed application? I'm confused, I don't know, which should I use.
1) when you try to have offline access, you get authorization code which may be redeemed for an access token and a refresh token.
For isntance:
https://accounts.google.com/o/oauth2/auth?access_type=offline
&approval_prompt=auto
&client_id=[your id]
&redirect_uri=[url]
&response_type=code
&scope=[access scopes]
&state=/profile
after you get authorization code, you cat get refresh token.
static Credential exchangeCode(String authorizationCode)
throws CodeExchangeException {
try {
GoogleAuthorizationCodeFlow flow = getFlow();
GoogleTokenResponse response =
flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();
return flow.createAndStoreCredential(response, null);
} catch (IOException e) {
System.err.println("An error occurred: " + e);
throw new CodeExchangeException(null);
}
}
See the section on Implementing Server-side Authorization tokens for more information.
and after you get refresh token , you must save it. see that sample for mor information.
2) If you don't have installed application, you should create web applications to change redirecting URL.

Getting user profile with google oauth2

I'm trying to get user profile information upon logging in with google-oauth2. User successfully logs in and i can get the access_token and can refresh the token when needed.
Though i could not manage to get any information about the user despite reading the docs and trying for hours.
From "Retrieving profiles" section of developers guide :
https://www.google.com/m8/feeds/profiles/domain/domainName/full
should be enough. i've tried with "gmail.com", "google.com", "gmail", "google", "orkut", "orkut.com" , myregisteredappsdomainname (and .com) as domainName. i've also tried it with
https://www.google.com/m8/feeds/profiles/domain/domainName/full?access_token=access_token_for_user
all i managed to get was 401 error, where it says "That’s an error.". Regarding 401 error, I've refreshed the token and tried again with new token, but kept getting 401s.
How can i get profile information and image address for user upon logging in?
The scope you're looking for is:
https://www.googleapis.com/oauth2/v1/userinfo
This has been already answered here
I was getting similar errors requesting profiles even after correctly defining the scope and getting access tokens etc.. The trick for me was to include the API version on my requests. See here for more info http://code.google.com/googleapps/domain/profiles/developers_guide.html#Versioning
Maybe little late yet could this be helpful to someone. Below is the working code I wrote to get gplus user profile
In HTML below markup will display goolge signIn button
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="YOUR GPLUS CLIENT ID"
data-cookiepolicy="single_host_origin"
data-scope="email">
</span>
</span>
Below is the java script
var access_token;
/**
* Called when the Google+ client library reports authorization status.
*/
function signinCallback(authResult) {
access_token = authResult.access_token;
gapi.client.load('plus', 'v1', function () {
gapi.client.plus.people.get({ userId: 'me' }).execute(printProfile);
});
}
/**
* Response callback for when the API client receives a response.
*
* #param resp The API response object with the user email and profile information.
*/
function printProfile(resp) {
if (resp.code != 403) {
console.log('name:' + access_token.givenname);
console.log('last name:' + access_token.lastname);
console.log('email:' + access_token.emails[0]);
console.log('gender:' + access_token.gender);
console.log('profile image url:' + access_token.image.url);
}
}
Please make sure that you load google api javascript asynchronously within the body tag as below
<script type="text/javascript">
(function () {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/platform.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
To handle logout refer to the answer I provide in below link, you will need to store access_token in backend so that during logout call this to be used, in my case I have stored in session and getting through ajax call
gapi.auth.signOut(); not working I'm lost
Hey why don't you look at the code given at:
http://www.codeproject.com/KB/aspnet/OAuth4Client.aspx
It definitely helps you. The project is actually an oauth playground to send correct oauth header to correct endpoints.

Resources