Thursday, 16 March 2017

How to verify facebook token and gmail acceess token and fetch user info.

Suppose that we didn't have facebook app_id, app_secret or gmail client_id and client_secret but we have to verify the provided token.

In this blog, we will verify token with using open graph api's of facebook. For sending a request we will use HTTParty.

Now in controller,

For Facebook -


    def verify_facebook_token
      token = params[:token]   
      response = HTTParty.get("https://graph.facebook.co/me?fields=email,name&access_token=#{token}")
          if response.code == 200
            user_data = JSON.parse(response.body)
      end       
    end

For Gmail -


    def verify_gmail_token
      token = params[:token]   
      response = HTTParty.get("https://www.googleapis.com/oauth2/v2/userinfo", headers: {"Access_token" => token, "Authorization" => "OAuth #{token}"})
          if response.code == 200
            user_data = JSON.parse(response.body)
      end       
    end


Above method return result like this -

    {"email"=>"er.sonukr@gmail.com", "name"=>"Sonu", "id"=>"416806898668956"}

Note - Gmail provides three types of token. i.e. id_token, access_token, refresh_token. We have to use access_token for userinfo api's.

1 comment: