August 3, 2015

Login by google account integration for Xamarin.Android and Xamarin.iOS

Brief: 
Google Account integration to the app, helps for the user authentication using their existing Google account and fetch profile information like email id,name and profile pic etc.
UPDATE: Mar 10,2017: It seems that google has been stopped webview approach for native applications. You can refer the solution provided by the xamarin doc.



In  previous post i explained How to handle Large and create Rounded corner imageHow to use Google Place API with Autocomplete in Xamarin AndroidIntegration of google map v2 in xamaron androidWorking on the wrong position and item click event issues with ListView in android xamarin.

Description:
To increase user friendliness in the application it is always recommended to avoid unnecessary lengthy form filling/Registration details,When the same can be achieved from the other sources like social network media.

This may also help to drive more users to your app by faster and easier way of registration process. Here I'm writing about Login by Google in Xamarin application android and iOS.
As of now there were no xamarin component which enables google account integration in Xamarin.Android.

Even i had posted this question earlier and  after going through  google developer documentation and xamarin forums helped me to get the work around,which I'm going to post here.

Implementation steps: 

1) Register in Google developer console 

a) Sign in to Google https://console.developers.google.com/ 
Select "Create an empty project" 


b) In the left sidebar, select "APIs & auth"
Find "Google+ API" and select it to "Enable API"


c) Again from Left menu Select "Credential". Click on "CREATE NEW CLIENT ID" this will open the pop up to configure Client Id.














Select "WebApplication"*
[*if we registered in developer console as installed application(like android) after making OAuth2Authenticator request it will show window with message "Please copy this code switch to your application and paste it there [code]" manually need to close the window and proceed to authentication. to get ride of this webapplication type is chosen]


Click on Configure Consent screen
This open ups screen "Consent screen", enter product name & remaining all fields are optional. Here selected Product logo will display during allow permission after login from app.




d) on selecting  "Save"  shows the Pop up screen where enter "Authorized redirect URIs".


Provide the redirect url with valid url (ex: "http://abcd.com/xyz.aspx") same should be used in the application code. [You can also use https://www.googleapis.com/plus/v1/people/me as redirect uri. It wont display in app even after redirection from login process].

you can leave blank "Authorized JavaScript origins" and Click "Create client Id". 


2.From  the application make an OAuth2Authenticator request. 
Use the xamrin component "Xamarin.Auth". Xamarin.Auth is an Cross-Platform API for authenticating user. So it can be implemented in both android and iOS.
Instantiate OAuth2Authenticator to make login request to Google Authorization Server,on successful authentication return the "access token".[Read more about token limit and expiration https://developers.google.com/identity/protocols/OAuth2

3.Google API Request to get Profile Information. Pass the access token over Google API[https://www.googleapis.com/oauth2/v1/userinfo?access_token=0}] to get user profile basic information.
This successful REST request returns user information in JSON format (How to make REST request and advantage)

4.Deserialize the JSON response to get data in class object.
Use the Xamarin component "Json.NET" to deserialize the json response.


Final Touch : This is the Cross-Platform approach to get the user authentication by google and works well in both android and iOS with sharing maximum code.


Code Snippet:


25 comments:

  1. Good One. Thanks. One Change

    var intent = auth.GetUI(activity);
    activity.StartActivity(intent);

    Should be call

    ReplyDelete
  2. Thanks Manikandan Sai.
    Here i have considered LoginByGoogle() method within the activity class. So in this case no need to take instance of activity to call.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
    Replies
    1. Thanks for your comment, but i won't allow unrelated ad link here

      Delete
  4. Hey Suchith, Thanks for the helpful post, however when i am trying this snippet nothing happens. it never hits auth.Completed

    ReplyDelete
    Replies
    1. I think might be mistake in OAuth2Authenticator initialization. re-check all the parameters

      Delete
  5. Thanks Suchith, i thought so too, but can't figure out. i have a redirect url but i thought i will leave this
    var auth = new OAuth2Authenticator ( clientId: "1111111-xxxxxxxx.apps.googleusercontent.com" ,
    scope: "https://www.googleapis.com/auth/userinfo.email" ,
    authorizeUrl: new Uri ( "https://accounts.google.com/o/oauth2/auth" ) ,
    redirectUrl: new Uri ( "https://www.googleapis.com/plus/v1/people/me" ) ,
    getUsernameAsync: null );

    ReplyDelete
    Replies
    1. Are you able to see google login window ? Recheck step1. and redirect url must be same as in developer console.

      Delete
  6. No its not showing me login window either also, i am calling this method from OnCreate, not sure if thats right place though. thanks for replying

    ReplyDelete
    Replies
    1. sorry small mistake in code snippet. check now, it should work.

      Delete
    2. Thanks Suchith, it worked for me.. Great work, saved a lot of my time.

      Delete
    3. Glad to know that it could helped you.

      Delete
  7. if user deny the Consent screen i need to set an intent xamarin android.. could you please help

    ReplyDelete
  8. I want an event when user clicks deny on consent screen android

    ReplyDelete
    Replies
    1. In that case "e.IsAuthenticated" will return false. so that you can decide it is denied/unsuccessful.

      Delete
  9. hi do you have sample project for this example?
    thanks

    ReplyDelete
  10. bro its working fine but in my case when i am press back button of my mobile its crashing with System.NullReferenceException: Object reference not set to an instance of an object how to handle this

    ReplyDelete
    Replies
    1. Hi, can you check what is null in author completed response. I think you are getting event instance as a null.

      Delete
  11. I'm getting invalid_grant error message in IOS. What would be the problem?

    ReplyDelete
  12. I got the access token but i am not able to get profile information. plz solve my issue

    ReplyDelete
  13. I got access token but i m not able to get profile information plz solve my issue.

    ReplyDelete
  14. my program is running on android but not running on the ios platform please give me the answer

    ReplyDelete
  15. NOW THIS WILL NOT WORK AS GOOGLE HAS REMOVED SUPPORT

    ReplyDelete
  16. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work... cydia impactor free

    ReplyDelete