Franklin Yu
Franklin Yu

Reputation: 9958

OAuth in Rails without cookies?

Typically OAuth in Rails is handled by OmniAuth, either directly used or with Devise. However, that does not seem to work in an API-only backend; OmniAuth relies on cookies and has its own (opaque) middleware, while cookies does not play very nice with native clients. That is why I am looking for a way to do OAuth without cookies. I am trying to build a website with separate frontend and backend; the workflow of OAuth through webpage, in my mind, is

  1. User clicks a button at my frontend, linked to the OAuth provider, with a callback at my frontend.
  2. User authenticates and authorizes in the provider page, and get redirected to my frontend with credentials.
  3. My frontend catches the token from query string, and sends them to the server to log in or register a new account, as AJAX. Server verifies and saves the token before responding with a session identifier.
  4. Future AJAX from frontend has the session identifier attached, either in some header or in query string.

I think I know how to do this from scratch; actually I have already created a Redis session store that ignores cookies at all, and the session identifier is extracted from Authorization header. (No, JWT is not the solution because it cannot be revoked easily. Redis can.) However I still wish to know if there is any solution ready to use, or whether Devise or OmniAuth already covers cookieless server.

FWIW, I am on macOS Sierra, every gem latest version.

Upvotes: 2

Views: 1075

Answers (1)

m3characters
m3characters

Reputation: 2290

I think you can provide a different session storage for omniauth: https://github.com/omniauth/omniauth#integrating-omniauth-into-your-rails-api

You can also disable cookie based sessions on devise, or simply override login/logout with your own flow.

And you can roll your own oauth flow, you can check some omniauth strategies to see how you can do it for each provider.

It's basically, redirecting through urls with certain parameters until you get the token.

On what I'm developing right now I basically use omniauth for logging in through Oauth2, and devise for email based log in. With omniauth I use the response hash to create my own session and I basically hijack devise sign_in to log_in with my own "method". Then I rely on that same session throughout the user experience.

Not sure how you could do it in terms of API, but as long as you can verify the Oauth flow went correctly and you have their email then just do whatever you regularly would do to keep them logged in.

Upvotes: 1

Related Questions