Search code examples
facebookfacebook-graph-apioauthkoala

Getting a user access token in facebook using Koala


I am writing a simple procedure that automatically makes a facebook post. From what I understand, I need to have a "user access token" to do this. I am using Koala (but the philosophy is similar for other libraries). Anyway, I create a new OAuth account:

@oauth = Koala::Facebook::OAuth.new(app_id, app_secret, callback_url)

The koala instructions then become somewhat unclear. The next two lines are:

@oauth.url_for_oauth_code # generate authenticating URL
@oauth.get_access_token(code) # fetch the access token once you have the code

Where does the "code" variable come from? It doesn't say in the documentation. Also, does the "get_access_token" method get an "app access token" or a "user_access_token"? The method name is not clear. I tried going to the url that the [url_for_oauth_code] method gave me, but it gives me no code! Where does the "code" variable come from?


Solution

  • On the front page of Koala it states you need to go through the OAuth process described at http://developers.facebook.com/docs/authentication/ (this is an old link but the content within is valid)

    Specifically

    @oauth.url_for_oauth_code
    

    https://github.com/arsduo/koala/blob/master/lib/koala/oauth.rb#L85 Generates a URL that you need to direct the user to based on the repo it's something like

    https://www.facebook.com/dialog/oauth?
        client_id={app-id}&
        redirect_uri={redirect-uri}&
        scope=email
    

    Based on the documentation https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2#login, when the response_type is omitted the default response type is code. So the above is equivalent to

    https://www.facebook.com/dialog/oauth?
        client_id={app-id}&
        response_type=code&
        redirect_uri={redirect-uri}&
        scope=email
    

    So on redirect to redirect-uri, this URL will be appended with the code param which you must handle then supply to

    @oauth.get_access_token(code)
    

    The access token is a user access token.