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,026
Last edited:

young61

Member
Licensed User
Longtime User
I'm having trouble with the following code while writing my Coinbase app. I have obtained the access code. What does the HttpUtils.postString actual do? I've pretty much followed the gmail tutorial but this just doesn't seem to work for my Coinbase app. When I manually input the commands in a web browser after I "Authorize" I get a blank screen and the authorization code in the url (see attached photos). This is where the problem begins.

B4X:
Sub GetAccessToken
    Dim postString As String
    'Msgbox("postString ","")
    postString = "grant_type=" & AuthorizationCode & "&code=CODE&redirect_uri=urn:ietf:wg:oauth:2.0:oob&client_id=" & clientId & "&client_secret=" & clientSecret
    Msgbox("postString " & postString & "","")
    HttpUtils.postString("GetAccessToken", "https://coinbase.com/oauth/token", postString)
    ProgressDialogShow("Sending authentication request...")
    Msgbox("Trying to Get Access Token ","")
End Sub

Sub Activity_Resume
    If HttpUtils.Complete = True Then JobDone(HttpUtils.Job)
End Sub


Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub JobDone (Job As String)
    ProgressDialogHide
    Select Job
        Case "GetAccessToken"
            Dim url As String
            url = HttpUtils.Tasks.Get(0)
            Msgbox("URL is " & url & "" , "")
            'Log(HttpUtils.GetString(url))
            If HttpUtils.IsSuccess(url) Then
                Dim Parser As JSONParser
                Parser.Initialize(HttpUtils.GetString(url))
                Dim m As Map
                m = Parser.NextObject
                AccessToken = m.Get("access_token")
                Msgbox("AccessToken is " & AccessToken & "" , "")
                'you may also want to get the refresh_token
                RequestAddressesList
            Else
                ToastMessageShow("Error getting access TOKEN", True)
                Button1.Enabled = True
            End If
        Case "AddressesList"
            Dim url As String
            url = HttpUtils.Tasks.Get(0)
            If HttpUtils.IsSuccess(url) Then
                ListView1.Clear
                XmlParser.Parse(HttpUtils.GetInputStream(url), "xml")
            Else
                ToastMessageShow("Error getting addresses list", True)
            End If
            Button1.Enabled = True
    End Select
    HttpUtils.Complete = False
End Sub
 

Attachments

  • SignIn.PNG
    SignIn.PNG
    32.2 KB · Views: 438
  • Authorize.PNG
    Authorize.PNG
    44.1 KB · Views: 487
  • AfterAuthorize.PNG
    AfterAuthorize.PNG
    15 KB · Views: 451

Descartex

Well-Known Member
Licensed User
Longtime User
Hi!!
I've a great little problem to implement one of the features of my new app, namely:
I have a Google account that I have added a number of calendar events, these events need to be read by my application so that, as add or modify one of them appears in the application.
For example:
The calendar stores meetings with the groups involved:
On March 31 at 10:15, the accounting group meet with the order the next day: (explanatory text of the meeting)
On the 10th of April the production group meet the following order: (explanatory text of the meeting)

I've been looking at Calendar2 library, but it gives me the info the calendar grabs the device associated account, not the account I wanted to ...

Maybe this can be the solution??
Thanks!!
 

Descartex

Well-Known Member
Licensed User
Longtime User
Is there any type of manual, tutorial or similar here???

Thanks a lot.
 

Descartex

Well-Known Member
Licensed User
Longtime User
Thanks a lot ;)
 

IDDGroup

Member
Licensed User
Longtime User
Ive been wracking my brains out on this to get it to work with cloud print.

I’ve gotten it to authenticate correctly, got the tokens and all. basically, all you have to do is change the scope to:

https://www.googleapis.com/auth/cloudprint”

Now the problem comes in when trying to do anything with it. for instance, to list all printers associated with the account, you are suppose to do this:

https://www.google.com/cloudprint/search?connection_status=all

which basically just takes the place of getting a “Contact list”. the error I’m getting is: “User credentials required”

From searching and reading, it appears that cloud print is expecting the http headers to contain the authorization code.

now i have been messing with this for 2 days straight now… can’t get it to work. the “Closest” i have come, was i added this to the “httputilseservice” program


req.SetHeader("Authorization: OAuth", Main.usercred)

under processnexttask. usercred is a global var that has the authcode. it should add it to the header, but its still getting the same error message.


If i could get this ONE thing to work, i can get the rest, but i am at wits end. i tried everything.



any suggestions or ideas?


like i said, all you should have to do is authenticate, and call that search command. for some reason, it appears that cloud print is just a little different than other oauth stuff.
 

IDDGroup

Member
Licensed User
Longtime User
It is simple to add headers to a request with HttpUtils2: Set HTTP Request Header with HttpUtils2

tried that too, didn't work either, the last attempt was chanig the headers using http which the program was already using (doing it in-stream which seemed to make more sense anyway).

I'm actually starting to wonder if there is something wrong with cloud print, i can't even find working samples in any language using oauth2 on the internet.
 

Douglas Farias

Expert
Licensed User
Longtime User
erel its possible get user profile info with this example ?
name
id
gender
etc etc
 

ValDog

Active Member
Licensed User
Longtime User
Erel,
I'm making use of the GMailContacts example code to work thru OAuth2 authentication with another entity (not Google). The example code works fine with Google, but I am a bit confused in that the wv_PageFinished sub is looking for a return URL of "https://accounts.google.com/o/oauth2/approval" - rather than the Google OAuth2 API-documented "redirect_uri" - what gives? According to Google's API, this return URL also should contain the authorization code - again, unlike extracting it from the WebView title. Can you please provide some clarification?
 
Top