szabcsee
szabcsee

Reputation: 433

How to get back to my Js App after authenticating with an Oauth server via Rails API?

I'm building an application with Rails 5 API and ExtJs. My ExtJs single page app loaded via the public/index.html.

I get redirected to the Oauth Login page with the required params via a button click in the ExtJs app.

Then the Oauth Server calls my Rails App and go through authentication and getting the token back.

All works fine. My problem is that now I have my user loaded, updated, access_token ready but I need to load the single page app in the browser and pass on the access_token. Somehow I can not manage this.

def login
if params[:code]
  response = request_token(params[:code])

  if response.header.code == '200'
    token_data = JSON.parse response.body

    user_info  = JWT.decode(token_data['id_token'],nil,false).first
    @user = User.find_by email: user_info['email']
    @user ? @user : @user = User.new

    @user.name = "#{user_info['given_name']} #{user_info['family_name']}"
    @user.access_token = token_data['access_token']
    @user.access_token_created_at = Time.zone.now
    @user.token_data = response.body
    @user.save


    render file: '/public/index.html'
  else
    redirect_to('/', status: response.header.code, alert: response.header.message)
  end
 elsif params[:error]
  redirect_to('/', status: 401, alert: params[:error])
 end
end

I either get stuck in an empty browser window with the localhost:3000 url and the code param or if I redirect I get a message with You are being redirected that reloads the window but I think the parameters are not passed on.

Upvotes: 1

Views: 139

Answers (1)

kansiho
kansiho

Reputation: 532

I usually use doorkeeper gem to create OAuth server and save redirect_uri to session[:return_to].

resource_owner_authenticator do
    session[:return_to] = request.fullpath
    current_user || redirect_to(new_user_session_url)
end 

Then after authentication, inject javascript

window.location = redirect_uri + params

OR create XMLHttpRequest to authentication server and then parse response like this:

parseAccessToken: function(response) {
    return {
      accessToken: response.match(/access_token=([^&]*)/)[1],
      expiresIn: response.match(/expires=([^&]*)/)[1]
    };
}

Upvotes: 0

Related Questions