How to get the auth URL from an OmniAuth provider without redirect

1k views Asked by At

How do you get the URL that OmniAuth redirect to when you go to /auth/twitter?

I am building an API server and just want to pass the URL in JSON to the client so it can do whatever it needs to with the URL.

I think what I want is the result of the strategy's request_phase as that looks to be the auth URL, but how do I get that in a new controller so I can do:

class MyOauthController < ApplicationController
  # GET /my_oauth/signin/twitter.json
  def signin
    url = ???
    render json: {signin_url: url}
  end

Is there a clean way to do this?

2

There are 2 answers

0
Evan Hammer On

Yes, Omniauth provides a helper function for you:

user_omniauth_authorize_path(key)
# for your case
user_omniauth_authorize_path("twitter")

Check out their Devise overview.

0
Ahgaigh8Ah On

Is there a clean way to do this?

Not directly, no - vanilla OmniAuth doesn't generate routes by itself. It uses something called "Rack middleware" which would intercept request outside of Ruby on Rails context and hence wouldn't need a Rails route to function.

The Evan's answer above is dependent on Devise gem, which is not strict requirement for OmniAuth (you may have it bundled & loaded or may not have it).

A cleaner alternative to blatant copy & pasting the relative route around may be some wrapper method/helper that could contain "/auth/twitter" reference to a single place/be more DRY.