Make Rails API mode support cookie (session) authentication

Summarize the changes when changing the authentication method of the application (Vue.js + Rails API mode) in onecareer from token authentication to session (cookie)

Why i started this

** Due to a requirement to seamlessly log in from an existing web app **

――How to seamlessly log in to the screen made by SPA for the user who logged in on the screen implemented by the ordinary web application. --Do you want to create an OAuth server? --It is necessary to use cookie (Session) authentication.

This time we changed to session authentication with priority on delivery date

What was needed for cookie authentication

Server side

config/application.rb

    # Only loads a smaller set of middleware suitable for API only apps.
    # Middleware like session, flash, cookies can be added back manually.
    # Skip views, helpers and assets when generating a new resource.
    config.api_only = false # <-Change false to true

If you want to make the session store a cookie, you can do it by setting config.api_only = true and loading the required middleware, but that's it.

--It doesn't go well with Devise. --If you use Devise, a lot of information will be added to the session, so it will not fit in the cookie. --The existing web application has session store as redis, so I want to use it.

Due to the above restrictions, I changed api_only to false. (Please tell me if there is a good way to use api_only = true and devise: bow :)

application_controller.rb (API base controller)

class ApplicationController < ActionController::API
  include ActionController::Cookies #<-Add this

This setting was also necessary when creating by inheriting the ActionController :: API.

Client side

axios (ajax library)

  axios.create({
    withCredentials: true,
    //...
  })

axios It is a function to send a different domain cookie, but session cookie could not be used unless this was enabled.

Recommended Posts

Make Rails API mode support cookie (session) authentication
[Rails] Use cookies in API mode
How to return Rails API mode to Rails
Nuxt.js × Create an application in Rails API mode
Rails6 [API mode] + MySQL5.7 environment construction with Docker
Rails (API mode) x React x TypeScript simple Todo app