Make Omniauth use json for callback?

I am trying to integrate Omniauth into an API written in rails that will be used by an Android application. This means that I want to be able to handle omniauth callback using JSON.

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

+4
source share
3 answers

You can specify the format in action when processing the 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 
+2
source

I managed to do this by checking the request object on my firewall.

When I make a request in my application, I add data about the view defining the format:

 format: "json" 

Omniauth then makes a callback to

 /auth/:provider/callback 

In my case, it matches

 sessions#create 

as an HTML request. But as soon as there, if you look at your request object in rails and search for the omniauth.params hash, you will see that one of the values โ€‹โ€‹is the format transmitted according to the initial request:

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

You are looking for this "format" => "json" as your mother and rendering json as an answer.

I hope it solves your problem.

+2
source
 # 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 in /auth/:provider/callback will return a default JSON response.

0
source

Source: https://habr.com/ru/post/1491034/


All Articles