maxluzuriaga
maxluzuriaga

Reputation: 1327

Force Omniauth to use json for callback?

I'm attempting to integrate Omniauth into an API written in rails, to be used by an Android application. This means that I want to be able to handle the omniauth callback with JSON.

By default, Omniauth sends its callbacks to /auth/:provider/callback, is there a way that I can force Omniauth to instead send its callbacks to /auth/:provider/callback.json?

Upvotes: 4

Views: 1739

Answers (3)

JesseG17
JesseG17

Reputation: 704

# app/controllers/users_controller.rb
def authenticate
  @credentials = request.env['omniauth.auth']
  render json: @credentials
end

# config/routes.rb
get '/auth/:provider/callback', to: 'users#authenticate', as: 'user_auth'

And then all requests made to /auth/:provider/callback will return a JSON response by default.

Upvotes: 0

RuiMochila
RuiMochila

Reputation: 185

I managed to do that by inspecting the request object on my rails backend.

When I make the request on my app, I add data on the submition defining the format:

format: "json"

And the omniauth then makes the callback for

/auth/:provider/callback

Wich in my case matches

sessions#create

as an HTML request. But once there, if you look at your request object in rails, and search for the omniauth.params hash you'll see that one of the values there is the format passed on tha data of the initial request:

"omniauth.params"=>{"format"=>"json", "provider"=>"facebook", "code"=>"..."} 

Its a mather of you searching for this "format"=>"json" and doing a render json as an answear.

I hope it solves your problem.

Upvotes: 2

TM.
TM.

Reputation: 3741

You can specify format in action where handling callback:

# in route.rb
match '/auth/:provider/callback' => 'authentications#create'

# in authentications_controller.rb
class AuthenticationsController < ApplicationController
  def create
    # your code here
    respond_to do |format|
      format.json { ... } # content to return
    end
  end
end

Upvotes: 2

Related Questions