Android Tutorial OAuth 2.0 / Google web services tutorial

This tutorial is no longer relevant. Google doesn't allow using WebView to access the server response. Updated tutorial: https://www.b4x.com/android/forum/threads/class-b4x-google-oauth2.79426/

OAuth is an authentication method which allows the user to grant your application access to private information in a controlled way.

In order to access private information you need to get an access token.

There are several steps required (the attached code takes care for most of the steps):
- Register your application with Google. You will get "client id" and "client secret" values.

SS-2012-01-30_17.36.26.png


In order to run this example you will need to first register a new application and fill ClientId and ClientSecret variables: https://code.google.com/apis/console


- In your application you should show a WebView that handles the authentication.
(the user default language is used in this dialog)
The scope parameter should be set based on the required service.

SS-2012-01-30_17.38.36.png


After the user approves the access the WebView is redirected to a different page. The authorization code appears in the page title. We extract it using WebViewExtender library. After extracting the code the WebView is removed.

- Another Http call is required to get the access token.

Once we have the access token we can send requests that access the user's private data.
In the attached example we retrieve the user Gmail contacts list.

OAuth 2.0 is a popular authentication method. It shouldn't be difficult to use this code with other web services such as Twitter, Facebook and others. It is much simpler than OAuth 1.0.
The following libraries are required: HTTP, JSON (to parse the access token request) and WebViewXtended (to get the authorization code from the WebView title).
The attached example also requires XmlSax for the contacts feed parsing.

You will need to register a new application with Google in order to run the example. Once registered you should fill CliendId and ClientSecret variables.
It takes two minutes to register a new application.
 

Attachments

  • GmailContacts.zip
    8.1 KB · Views: 1,019
Last edited:

stevel05

Expert
Licensed User
Longtime User
Thanks Erel, I've just been banging my head against the wall looking at the Facebook API, it did occur to me that using HTTP may be a simpler solution and you have provided it.

I'll have a look at Google first, then Facebook later.

Thanks

Steve
 

salvatore75

Member
Licensed User
Longtime User
I'm going crazy for a http post to Google Fusion tables !!!!!!!!
I modified the example gmailcontacts OAuth 2.0 / Google web services tutorial for accessing google fusion tables. I get the access_token but the on HttpUtils.PostByte i get in sub hc_ResponsError StatusCode = 400 & Reason = "parse error near access_token" !!!

Erel Help me I'm crazy, I tried in a thousand ways!

here the code:

Dim su As StringUtils
Dim bytes() As Byte
Dim sdata As String
Dim GoogleFusionPath As String
Dim query, auth, tail As String

GoogleFusionPath="https://www.google.com/fusiontables/api/query"
query="INSERT INTO 842604 (Barcode, GPS, Data) VALUES ('22222222', '10.1 11.1', '28/01/2012')"

auth="&access_token="& AccessToken
tail = "&jsonCallback=?"

sdata = "sql=" & su.EncodeUrl(query & auth & tail ,"UTF8")
bytes=sdata.GetBytes("UTF8")

HttpUtils.PostBytes("INSERT",GoogleFusionPath,byte s)
 

margret

Well-Known Member
Licensed User
Longtime User
No Email or Website Data

Hello, I have an issue I hope you can help with. I am using the OAuth 2.0 Tutorial Code Erel wrote. In the code listed below, it does not return any Emails or Websites, it return every thing else, Notes, Phone #'s, etc. I have logged on to Google with a PC and created a half dozen contacts with all the fields filled in. Now I run this code with just the message box to display the field names and values passed to XML_EndElement and all works but the email and websites. It does return as the Name of Field but the Text is always blank, even though they are populated in Google's contacts. All other fields return their respective data just as they should. Any Ideas?

[CODE]
Sub XML_EndElement (Uri As String, Name As String, Text As StringBuilder)
Msgbox(Text & CRLF & CRLF & Uri, Name)
End Sub
[/CODE]
 
Last edited:

margret

Well-Known Member
Licensed User
Longtime User
@Erel, I really don't understand this stuff, but looking through the Google information, I found this:
-----------------------------------------------------------------------
To retrieve all of a user's contacts, send an authorized GET request to the following URL:

https://www.google.com/m8/feeds/contacts/{userEmail}/full

In your sample you used:

https://www.google.com/m8/feeds/contacts/default/full

I changed the above line to the feed with the [userEmail] in it and I get the same response. This is from the docs of Google Contacts API-3. Any other info you might can provide a blind horse?
 

thedesolatesoul

Expert
Licensed User
Longtime User
Hi margret,
Try as Erel says for a single contact using:
B4X:
https://www.google.com/m8/feeds/contacts/{userEmail}/full/{contactId}
Get the contactid from the first request.
Or even better try:
B4X:
https://www.google.com/m8/feeds/contacts/default/full?updated-min=2007-03-16T00:00:00

Are you sure it does not return only the email addresses?
Because there is a 'max-results' limit which means mostly the old contacts are returned and the new ones you added are not returned.
Also, I had some problem due to contact groups. I think the 'My Contacts' group is not returned unless forced.
The API is a bit temperamental, you might have to experiment.
 

margret

Well-Known Member
Licensed User
Longtime User
It does not return the email or the websites that were entered. The maxlimit is set to 100. This is not a problem as I just created this google email, so it's new. I then added six contacts and that's all there is. I get the notes, multiple phone #s, etc. I just get a blank/empty value for email addresses and website urls even though they are there. In the message box the header does come up and says, but the text is blank. The same is true for the website, it comes up in the header of the message box but the text is again blank. I will try it again getting a single contact with the id and see if it's any different.
 
Last edited:

margret

Well-Known Member
Licensed User
Longtime User
Update

I went back and tried one contact at a time, I get the same results. This time I wrote the order of the data coming in. The msgbox() displays the name of all entries I am looking for it is just that the birthday, emails and websites return blank. The fields below are what's returned and they are returned in this order. You can see after it starts sending blanks, there are fields after that, that return the correct data:

B4X:
updated = correct data
edited = correct data
title = correct data
content = correct data
fullName = correct data
givenName = correct data
familyName = correct data
name = correct data
birthday = blank
email = blank
phoneNumber = correct data
phoneNumber = correct data
phoneNumber = correct data
formattedAddress = correct data
street = correct data
postcode = correct data
city = correct data
region = correct data
structuredPostalAddress = correct data
website = blank
website = blank
website = blank
website = blank

This happens on all six contacts in the Google contacts. There are only six contacts total.
 
Last edited:

keirS

Well-Known Member
Licensed User
Longtime User
Cant seem to get this to work. When I register my app Google doesn't give me a client secret. I have a client ID and it shows me the package name of the app and the SHA1 certificate fingerprint of the keystore file for the app which I got from running the the keytool program distributed with Java but it doesn't show me a client secret?

Z7eOxSSd.jpg
 

keirS

Well-Known Member
Licensed User
Longtime User
I actually got the example working by creating a new client id and selecting application of type "other" which gives me a client secret. I would be useful to know how oAuth works with the application type "android" though. Couldn't find any examples of how this might work in the Google API documentation as the examples all appear to use client secret which you don't get when selecting android as the application type.
 

sally3599

Member
Licensed User
Longtime User
where is the debug keystore located

For B4A, where is the debug keystore located?
B4X:
keytool -exportcert -alias androiddebugkey -keystore path-to-debug-or-production-keystore -list -v

Any help will be appreciate it.
 

sally3599

Member
Licensed User
Longtime User
OAuth 2.0 for Installed Applications

Yes, create a Client ID for Installed application on Android, it needs to run the Keytool command to generate the signing certificate's SHA-1 fingerprint first.

https://developers.google.com/console/help/#installed_applications

I use the Client ID & Client Secret for Web application, it will show a error about Redirect URI.

So what's the "path-to-debug-or-production-keystore" you using?

B4X:
keytool -exportcert -alias androiddebugkey -keystore path-to-debug-or-production-keystore -list -v
 
Top