Unable to validate Authenticity Token when POST `/auth/:provider` to avoid CSRF error
Author: tonyltfCreated Sep 25, 2024Updated Feb 17, 2026
Configuration
- Provider Gem:
omniauth-oauth0 - Ruby Version:
2.7.8 - Framework:
Rails 6.0 - Platform:
Debian 12
Expected Behavior
I am making the user login on my Frontend React app with POST /auth/auth0
Rails API to get authenticity token
class SessionsController < ActionController::Base
def csrf_token
render json: { csrf_token: form_authenticity_token }
end
endFrontend I tried a few ways
const csrfToken = await getCSRFToken();
axiosInstance.defaults.headers.common['X-CSRF-Token'] = csrfToken;
const formData = new FormData();
formData.append('authenticity_token', csrfToken);
const response = await axiosInstance.post('/auth/auth0', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});or
const csrfToken = await getCSRFToken();
axiosInstance.defaults.headers.common['X-CSRF-Token'] = csrfToken;
const response = await axiosInstance.post('/auth/auth0', {
'csrf-param': 'authenticity_token',
'csrf-token': csrfToken,
authenticity_token: csrfToken,
});I expect this will be the same as link_to 'Sign in via X', '/auth/:provider', method: :post
Suggested in https://github.com/omniauth/omniauth/wiki/Resolving-CVE-2015-9284#mitigating-in-rails-applications
Actual Behavior
I always get ERROR -- omniauth: (auth0) Authentication failure! ActionController::InvalidAuthenticityToken even I send the CSRF token or authenticity token in the request
Source: omniauth/omniauth