Search code examples
oauth-2.0mobile-applicationstackexchange

Using stackexchange's OAuth for logging into mobile app


I'm making a hybrid app on Android based on StackExchange's APIs. I need to provide the login feature in it. I'm following the steps described in their JS SDK http://api.stackexchange.com/docs/js-lib. I'm able to get the SE.init executed successfully, however SE.authenticate gives an error like 'Unexpected domain on proxy URL'. Now my app's url is having localhost:8080 in its domain, which i specified in the channelUrl property of SE.init. Even if I run it on android device, its domain is like file:///data/data... something like that. So how do i workaround this?

In this whole process, when my browser is launched after clicking on login in my app, i do see stackexchange's various login options like login through google, facebook etc. But problem that i described above happens after i click on say, google, to login. so it tries to redirect and it finds that i have specified a localhost domain in the channelUrl in SE.init


Solution

  • I had a similar problem, so I will share my findings with the hope that it would be useful to you or someone else dealing with the same issue.

    Firstly, the registered domain for your app must match the domain you provide in your channelUrl. An important point to note here is that the following are not considered to be the same domains:

    `example.domain.com` and `example.domain.com:8080`. 
    

    Many browsers would see this as a cross-domain post and hence you may end up getting errors of the following:

    Unable to post message to example.domain.com. Recipient has origin example.domain.com:8080

    This is to prevent cross site scripting attacks.

    What worked for me? : I realized that it would be a real big pain to deal with the idiosyncracies of localhost stuff. I hence registered my application on a cloud hosting service like Heroku ( you can choose any of the available ones, I chose Heroku for it's quick and hassle free registration for beginners and a nice toolbelt set.). Post that my domain is now myapp.herokuapp.com. Once, I specify this within the OAuth domain for the StackExchange application and modify the channelUrl parameter to contain myapp.heroku.com/blank.html, it all started working and I am now able to fetch data using the StackExchange API.

    I am posting the link to my discussion with the StackExchange support folks that helped me come to this solution.

    Hopefully, this points you towards a solution.