2 years ago
#4335
Aaron Parisi
Rails API + React Frontend - how to make CSRF cookie NOT httponly?
I have a Rails 6 API and a React frontend and I would like to keep verify_authenticity_token
on all controller actions.
Backend sets CSRF token as follows in application_controller.rb
:
class ApplicationController < ActionController::Base
...
include ActionController::Cookies
after_action :set_csrf_cookie
...
protected
def verified_request?
super || request.headers['X-CSRF-Token'] === cookies['X-CSRF-Token']
end
def set_csrf_cookie
if protect_against_forgery? && current_user
cookies['X-CSRF-Token'] = {
value: form_authenticity_token,
httponly: false
}
end
end
end
Frontend is attempting to use js-cookie to retrieve cookies. I have the following in a cookies.js
file:
import Cookies from 'js-cookie'
const getCSRFToken = () => {
window.Cookies = Cookies;
const token = Cookies.get('X-CSRF-Token')
return token
}
export default getCSRFToken
and I call this function when I create an Axios request. The function to build the request takes params like method, url, data, etc.:
export const newAxiosIns = params => {
// params will be a hash of various headers
const defaultParams = {
baseURL: baseUrl,
withCredentials: true,
headers: {
common: {
'X-CSRF-TOKEN': getCSRFToken()
}
}
}
const axiosIns = axios.create(defaultParams)
return axiosIns(params)
}
But the cookies end up being httponly
in Chrome:
I wondered if it had to do with the form_authenticity_token, so I made a fake token with a value of 'faker' but that was also not httponly
.
Thanks!
reactjs
ruby-on-rails
api
csrf
httponly
0 Answers
Your Answer