Android OAuth with valid "CONSUMER_KEY" and "CONSUMER_SECRET" - java

I have a valid consumer_key and consumer_secret for my app to access resources on a certain website.
I create the consumer like this:
private void createConsumer(){
mConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
}
I create the provider like this:
private void createProvider(){
mProvider = new CommonsHttpOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL,
AUTHORIZE_URL);
}
I then use an AsyncTask to retrieve what I assume is a valid AccessToken from the server.
mAccessTokenUrl = mProvider.retrieveRequestToeken(mConsumer, CALL_BACK_URL);
with this call I get something similar to this:
``http://www.mygarden.org/oauth/authorize?/oauth_token=XXXXXXXXXXXXXXhs343sjd&oauth_callback=http%3A%2F%2Flocalhost
I'm assuming the token is correct because if I test this with the incorrect credentials I don't get anything back.
Question 1:
Is this callback url corrent, because on the site it does not specify a callback url, just the app's website; and how should I use it on the android app?
Question 2:
How do I now use the Access Token to consume certain services on the website, for example to get all the plants I should use this link: http://api.mygarden.org/activities/all which should return certain data in xml/json format
Extra information is that all calls to the API should use the http GET method unless specified otherwise. I do not want the user to first register on the site, I just want to consume the services they provide using my app's access credentials. If user credentials are necessary, could I embed them within the URL and grant the user access automatically?
The website is: http://www.mygarden.org
Thanks for your help.

To get a list of all the plants you don't need to authenticate a user. This is only necessary for user related actions, like posting status updates or adding plants to your garden.
So you only have to send a call to oauth/request_token and then oauth/access_token, after that you're ready to get some data from the API
Answer for Question 1:
If your developing an android application you don't need the callback url, this is needed when you want to authenticate a user trough a website. Make sure you select Client in the app settings on mygarden.org
Answer for Question 2:
To get all the plants you need plants/all. If you're using a standard oauth library, all the required oauth parameters are automatically added to your query
I'm a developer at mygarden.org, you can always contact our support ;)

Related

JAVA youtube api allow users to upload to my channel without login

I was playing around with youtube api samples that they provide in this link
with JAVA
I can search for videos upload videos to specific channel and all the code that they provide works fine.
the only problem I face is "when I try to upload it opens my default browser and asks me to sign in"
like this screenshot.
here is what in my head I know it's not that simple it's just a imagination of what I want to achieve.
// String myaccount = "username#gmail.com"
// String mypassword = "123456789"
// String mychannel_id = "UCU7mv98lde1hon2DXIgGMKg"
// signin(myaccount,mypassword,mychannel_id);
// upload(video.mp4);
what I have:
client_id, client_secret in json file
the channel id, account, and the password
i was searching for about a day and all i got is ..
access token
,Token Service API
,identity toolkit api
,onBehalfOfContent,onBehalfOfContentOwner
however I don't know how they work or where I can get them
finally I have small idea I traced the code and I found it saves a file with all credentials in C://users/user-name/.oauth-credentials
it's not readable but it seems like it is used to authorize the account with the password and channel id
can I use this?
would it expire for any reason and i have to refresh and if so how can I refresh it?
thanks for help BTW

Google API Authorization Using Scribe OAuth Java Library

I am trying to make a Java class which would call upon Google's API to recreate an access token to a user's account with new permissions/larger scope. This class is to be instantiated by a Java servlet I had created. I want a function within that class to return a new access token. For this class to do that, I am using the Scribe library.
In Scribe's quick guide, there are two steps which concern me and have me stumped:
Step Three: Making the user validate your request token
Let’s help your users authorize your app to do the OAuth calls. For
this you need to redirect them to the following URL:
String authUrl = service.getAuthorizationUrl(requestToken);
After this either the user will get a verifier code (if this is an OOB
request) or you’ll receive a redirect from Twitter with the verifier
and the requestToken on it (if you provided a callbackUrl)
Step Four: Get the access Token
Now that you have (somehow) the verifier, you need to exchange your
requestToken and verifier for an accessToken which is the one used to
sign requests.
Verifier v = new Verifier("verifier you got from the user");
Token accessToken = service.getAccessToken(requestToken, v); // the requestToken you had from step 2
It does not seem to specify how to get that verifier from the user. How am I supposed to do that? How do I redirect my user to the authURL, and how do I get it to send its verifier back to this class of mine, which initiated the request to begin with?
If this is unclear, let me structure the question differently, taking Scribe out of the equation: To get an authorization code from Google (which would be used to then get a refresh token and access token), I would execute the following URL connection from within the servlet (yes, I've tried to answer this problem without the Scribe library, and still can't figure it out):
URL authURL = new URL("https://accounts.google.com/o/oauth2/auth");
HttpsURLConnection authCon = (HttpsURLConnection) authURL.openConnection();
authCon.setRequestMethod("GET");
authCon.setDoOutput(false);
authCon.setConnectTimeout(100000);
authCon.setRequestProperty("response_type", "code");
authCon.setRequestProperty("client_id", CLIENT_ID);
authCon.setRequestProperty("redirect_uri",
"http://**************.com/parseAuth/");
authCon.setRequestProperty("scope", convertToCommaDelimited(scopes));
authCon.setRequestProperty("state", csrfSec);
authCon.setRequestProperty("access_type", "offline");
authCon.setRequestProperty("approval_prompt", "auto");
authCon.setRequestProperty("include_granted_scopes", "true");
What has me stuck is what I should be putting for the redirect URI. After getting the user's approval for the new scope, this authorization URL would return an authorization code to the redirect URI, and seemingly nothing to whatever called it. (Am I correct in this?) So if I have another servlet as the redirect URI to parse/extract the authorization code from the response, how in the world do I get that authorization code back to my first, initial servlet? It seems to me that there is no way to have it give back the value to the servlet, in the same position of the code from which the URL was called. It looks like the function has to end there, and all new action must take place within that new servlet. But if that is the case, and I send that auth code to Google's API which would send back a refresh token and access token to ANOTHER servlet I would make to be its redirect URI, how do I possibly get that information back to what it is which called the initial servlet to begin with? That seems to be the same problem at its core, with the problem I am having with Scribe.
I've been stuck on this for many hours, and can't seem to figure out what it is I am supposed to do. I feel like I am missing some key concept, element, or step. I need this clarified. If it is at all relevant, my servlet is hosted on a Jboss application server on OpenShift.

Magento customer authentication via API

I am using Magento with a 3rd party Java Web Application.
My application is "connected" to Magento via Magento SOAP API V2.
How can I perform a Customer Authentication from my Java aplication (outside of Magento) via api?
Any help would be appreciated.
I came up to a solution on how to login a customer via SOAP API and I will post it here so it can be helpful for others.Here is what I did to make it work:
I created a custom module in Magento with a custom method that login a customer and retuns the sessionID that is set on server side.
Mage::app()->setCurrentStore($website);
// Init a Magento session. This is super ultra important
Mage::getSingleton('core/session');
// $customer Mage_Customer_Model_Customer
// We get an instance of the customer model for the actual website
$customer = Mage::getModel('customer/customer')
->setWebsiteId(Mage::app()->getStore()->getWebsiteId());
// Load the client with the appropriate email
$customer->loadByEmail($email);
// Get a customer session
$session = Mage::getSingleton('customer/session');
$session->loginById($customer->getId());
if ($session->isLoggedIn()) {
return $session->getSessionId();
} else {
return null;
}
I created a Magento Custom Api so I can call my login method via SOAP.
Call the login method from my JAVA app, get the sessionId, then set the cookies on the browser, based on received sessionId.
http://yourmagentohost/setCookies.php?sessionId=your_session_id
And inside setCookies.php you have: setcookie("frontend", $_GET["sessionId"] , time()+3600);
That's it, now you have a logged in customer.
How can I perform a Customer Authentication from my Java aplication
(outside of Magento) via api? SOAP API V2
Clarification:
API Users (at least Soap) and Customer's are two user types. If you have a pre-existing userlist, and are looking to find out if they exist as user's inside of Magento, you may retrieve email account's and their related attributes and corresponding password hash's (CE: md5:salt , or CE/EE: sha:salt) all via SOAP. If you are looking to do comparative operations, you will need to implement the same Hashing against your password's to do 1:1 comparisons. If you are looking to have your Application use SOAP to directly perform operations, I would make sure that there is a layer of abstraction, as your app could be used nefariously targeting other user id's all depending on the SOAP Role and ACL set in Magento's Admin.
Moving on...
V2: You'll have to swap to Java, ex: PHP.
$username 'yourUsername';
$password = 'yourApiKeyPlainText';
$proxy = new SoapClient('https://www.yourdomain.com/magento/api/v2_soap?wsdl=1');
$sessionId = $proxy->login($username, $password);
//Get a Full customer List from Magento
$customerList = $proxy->customerCustomerList($sessionId);
//get back a list
//Target a user from your List, Compare Details against your App
$customerInfo = $proxy->customerCustomerInfo($sessionId, '2'); //Customer Id
Remote operations, like Checkout, can be rather involved. The question remains, what do you wish to do next to, or on behalf of the user with your app?
References:
http://www.magentocommerce.com/api/soap/customer/customer.list.html
http://www.magentocommerce.com/api/soap/customer/customer.info.html
Cheers,
Your code example does not use SOAP. Magento SOAP accesses actually look like the following:
$client = new SoapClient('http://magentohost/soap/api/?wsdl');
// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');
Have a look at the API documentation: http://www.magentocommerce.com/api/soap/introduction.html

How to provide a Twitter PIN statically during OAuth authentication

http://twitter4j.org/en/code-examples.html - How to provide a Twitter PIN statically during OAuth authentication, the code example talks about providing a PIN if its already available.
Our application is a standalone java application and would prefer to pass credentials via a property file without any human intervention.
Twitter will provide you the PIN code.
In the example, Twitter4J supposes that somebody will copy the URL it gave (with requestToken.getAuthorizationURL() at line 10) in a web browser and will authorize the application via the browser. After that, the user is supposed to write in the example program the PIN code displayed in its browser.
There are two big drawbacks for you in this example :
Human intervention
Which code will you give to your example program if Twitter do not give you a PIN code (and it will happen if the callback URL of your Twitter application is not "oob") ?
You will have to simulate the human intervention to get the PIN code. Unfortunately, Twitter4J does not seem to get methods to do this (I do not see such method in the Javadoc) so you will have to code yourself the following process :
Retrieve the HTML code of the web page at requestToken.getAuthorizationURL().
This HTML page contains a form whose some parameters will be posted with the username (or email) and the user's password to get the PIN code. These parameters are called "oauth_token" (the temporary OAuth token that you already have), "deny" (a tag used if you do not want to authorize the application) and "authenticity_token". All of them are in <input> HTML tags. Pick them.
Simulate the posting of the form. For this you will have to use the POST oauth/authorize endpoint. The URL is https://api.twitter.com/oauth/authorize?oauth_token=<your OAuth Token>. The request has to be authenticated following the Twitter process for Authenticating requests. This is the content of what you will post : "authenticity_token=<the form's "authenticity_token" parameter>&session[username_or_email]=<user's name or email>&session[password]=<the user's password in clear>". If you don't authorize the app, append "&deny=<the form's "deny" parameter>" in the body message. There will not be any problem for you since you have got the credentials (session[xxx] parameters) in a property file and you picked the other parameters in the form (cf 2.).
The Twitter API will give you back an web page. If the authorization was successful, the PIN will be inside. However, be careful. The PIN takes different names depending on the callback URL. If the callback URL is "oob", the PIN code is called OAuth PIN. It is a 4-digit number somewhere in a <div id="oauth_pin"> HTML tag. Otherwise, it is called OAuth Verifier. It is contained in a URL located in a <div class="happy notice callback"> HTML tag. In this URL, the PIN is the oauth_verifier of the request string. It looks like an OAuth token.
Don't hesitate to have a look at the HTML code of the web pages of the 2nd and the 4th step of my process. It is very useful to understand the process.
I spent some time today trying to figure out how to authenticate without user intervention using Twitter4j Library. I came up with the following:
ConfigurationBuilder conf = new ConfigurationBuilder();
conf.setOAuthConsumerKey(CONSUMER_KEY);
conf.setOAuthConsumerSecret(CONSUMER_KEY_SECRET);
conf.setOAuthAccessToken(TOKEN);
conf.setOAuthAccessTokenSecret(TOKEN_SECRET);
Twitter twitter = new TwitterFactory(conf.build()).getInstance();
By using ConfigurationBuilder, I'm now able to authenticate automatically. Of course you need to set values for CONSUMER AND TOKEN keys accordingly. Here's how I verified it:
User user = twitter.verifyCredentials();
System.out.println("Successfully verified credentials of " + user.getScreenName());
Hope this helps!

Google Client Login Handling AuthToken

I have a non-gae, gwt application and it have a module that allows users to create documents online via google docs api.
To do that, i first ask user to enter the name and type of the document, than create a new document via google docs api with the given parameters and onSucces part of that servlet returns edit link which is used in client side to open a new page to edit the created document.
Problem that, eachtime i try to open that editLink user have to enter login informations. To solve this i try to use Google Client Login but i am totally lost i think.
First i have username and password of user and can directly use them, after searching i tried some examples which usually returns a token like this and that. Now what should i do with token? How can it be used to complete login process or should totally find another way to do login? All those oauth1,oauth2 and etc. documentations confused me a little bit.
here are my steps;
Server side;
LinkedHashMap<String, String> hashMap = new LinkedHashMap<String, String>();
// Login
DocumentList docList = new DocumentList("document");
docList.login(ServletUtil.googleDocsLoginInfo().get("username"), ServletUtil.googleDocsLoginInfo().get("password"));
//Create document with a unique suffix
String docName= parameterName+ "-Created-" + new Date();
docList.createNew(docName, dosyaTur);
// Find the created document and store editLink
DocumentListFeed feed = docList.getDocsListFeed("all");
for (final DocumentListEntry entry : feed.getEntries()) {
if (entry.getTitle().getPlainText().equals(docName)) {
hashMap.put("editlink", entry.getDocumentLink().getHref());
}
}
return hashMap;
And Client side;
#Override
public void onSuccess(LinkedHashMap<String, String> result) {
String editLink = result.get("editlink");
Window.open(editLink,"newwindow","locationno");
}
Thanks for your helps.
If I may suggest using OAuth instead of Client Login, which is outdated and less secure.
The functionality is basically the same (for OAuth 2.0 there are more ways to handle the login).
I know, trying to understand how to access the api via OAuth is very confusing, so I try to break it down a little:
If you use OAuth 2.0 you may want to use a library like this one or you can try out my own (although I wrote it for Android, this could work with other Java Apps including Web Apps)
This is what happens when a user logs in the first time with your app:
> Your App sends an authorization request containing some information about your app - for example your app needs to be registered with google and therefore has a special application key
< The Server sends you a url, open it in a new browser window and let the user login. There he will be asked to allow your app to access his account (or some parts of it) - when he confirms he will be prompted an Authorization Code which he needs to copy
> The user gets back to your app, where you will ask him for the authorization code. After he gave it, your app connects again with the server and sends the code as some kind of authorization grant of the user.
< The Server answers with a access token
All you need to do is use this access token (also called a bearer token) in all your requests to the server hidden in the header message.
I am sorry I can't give you a more precise answer right now, since I never used GWT. All I can say is, try using OAuth2, it is actually very simple (after you learn what all this confusing things like authorization flow, bearer token etc are) and really comfortable for your user, once the he has done the first login.

Categories