Every time I attempt to make a "post" request to the SailsJS server, I encounter a 403 CSRF Mismatch error

Having an issue with my sailsJS server. I am attempting to send a post request from a client on a different domain.

I am sending _csrf from /csrfToken, but encountering a 403 csrf mismatch repeatedly.

The client-side code appears as follows:

    $.ajax({
                  url: 'http://myserverdomain.ru/csrfToken'
                  success: (response) ->
                      $.ajax({
                          url: 'http://myserverdomain.ru/session/create'
                          type: "POST"
                          crossDomain: true
                          xhrFields: {
                              withCredentials: true
                          }
                          data: {_csrf: response._csrf, email: 'mail@mail', password: 'password'}
                          error: () ->
                              console.log 'error'
                          success: ( resp ) ->
                              console.log resp
                      })
            })

Server configurations:

module.exports.csrf = {
    grantTokenViaAjax: true,
    origin: 'http://myclientdomain.ru'
};


module.exports.cors = {

  allRoutes: true,

  origin: 'http://myclientdomain.ru',

  credentials: true,

  methods: 'GET, POST, PUT, DELETE',

  headers: 'content-type'

The response shows:

CSRF mismatch

General information:

Remote Address:ip.ip.ip.1:1010
Request URL:http://myserverdomain.ru/session/create
Request Method:POST
Status Code:403 Forbidden

Requested headers:

Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
Content-Length:95
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:sails.sid=s%3A_HBoGJvI9N_-kH3Bj2LBrIrayWAb_k4z.N9P%2F%2Bt%2FDWCFAuK1MvBNjyYO1ntmp5m8a5Te0IM%2Ftn7s; BCSI-CS-c82c2a7dcc10e8b5=2
Host:myserverdomain.ru
Origin:http://myserverdomain.ru
Proxy-Connection:keep-alive
Referer:http://myserverdomain.ru/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36

Form data sent:

_csrf:ljGDMpSr-_O1ktMJ-zHEJfWaKPygXwNSSjcU
email:mail@mail
password:password

Need assistance, please!

Answer №1

Although I am not well-versed in SailsJs, looking through their Documentation for a few minutes gives me the impression that your approach is correct. However, I would suggest trying a couple of adjustments:

  1. Ensure to set _csrf in the header.
  2. Modify the origin value in the module.exports.csrf to *
    
    module.exports.csrf = {
       grantTokenViaAjax: true,
       origin: '*'
    }
    

Answer №2

Remember to include it in the header

Insert X-CSRF-Token:

$.ajax({
url: 'http://myserverdomain.ru/csrfToken'
success: (response) ->
  $.ajax({
      url: 'http://myserverdomain.ru/session/create'
      type: "POST"
      crossDomain: true
      beforeSend: function(xhr, settings){
          xhr.setRequestHeader('X-CSRF-Token', '_YOUR_CSRF_CODE_HERE_');
      }
      xhrFields: {
          withCredentials: true
      }
      data: {_csrf: response._csrf, email: 'mail@mail', password: 'password'}
      error: () ->
          console.log 'error'
      success: ( resp ) ->
          console.log resp
  })
})

Answer №3

To set up CSRF protection in your application, include the following code snippet in your config/crfs.js file:

module.exports.csrf = {
  enableAjaxTokenGrant: true,
  disabledRoutes: '*Route URLs*',
  origin: '*'
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes my local storage to be cleared whenever I refresh the page in React with Redux?

What causes my local storage to reset to empty whenever I refresh the page? I am attempting to save data to local storage that is also passed to my redux state, but I am unable to do so. const retrieveLocalStorage = () => { const oldExpenses = JSON ...

Users may find that their Liferay session unexpectedly expires, even while they are actively engaging in activities on

My webpage contains a portlet that dynamically loads content using AJAX calls to resource URLs. Despite the user being actively engaged on the page, we are experiencing session expiration issues. Why could this be occurring? ...

Fade out all the other images using jQuery

I have created a jQuery code to fade images, but when I move the mouse over them all images fade simultaneously! $(".playThumb").fadeTo("normal", 1); $(".playThumb").hover(function() { $(".playThumb").each(function() { if ( $(this) != $(this) ...

What are the best practices for securely storing SSL certificates and public/private keys?

I possess keys that appear like this. MIID0DCCArigAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJGUjET MBEGA1UECAwKU29tZS1TdGF0ZTEOMAwGA1UEBwwFUGFyaXMxDTALBgNVBAoMBERp bWkxDTALBgNVBAsMBE5TQlUxEDAOBgNVBAMMB0RpbWkgQ0ExGzAZBgkqhkiG9w0B CQEWDGRpbWlAZGltaS5mcjA ...

Error: JQuery cannot locate the specified PageMethod

I've been attempting to retrieve information from a PageMethod using jQuery and AJAX, but so far, I haven't had any success. While debugging the process, I noticed that the error part was triggering. Upon using the debugger in Visual Studio, I d ...

Access Denied: Unauthorized token detected in Symfony 5.4

Running Symfony 5.4 in a development environment (docker) allows successful logins. However, attempting the same login via docker in production results in the following error message: {"message":"Invalid CSRF token."} The issue seems t ...

Enhancing OpenAI API Responses with WebSocket Streaming through Express Middleware Integration

  Currently, I am in the process of developing an Express.js application that requires integration of OpenAI's streaming API responses to be transmitted in real-time to a front-end via WebSockets. Even though I have established communication between ...

ensure that angular's ng-if directive sets aside space to display content when triggered by an event

I'm facing an issue with my modal form setup where if a text-field is left blank, a label saying "it is required" is generated below the field, causing the "Proceed" button to move (along with all other elements below it). How can I make sure that DOM ...

Redux action intensifies upon socket events

I have a Reactjs and Redux application that works well with axios. However, I would like to integrate socket.io into it. In my redux action, I tried the following: export const getOne = (id) => async dispatch => { socket.emit('getOne', i ...

Discover the best way to integrate your checkbox with your Jquery capabilities!

I am having trouble getting my 3 checkboxes to interact with the JQuery button I created. The goal is for the user to be able to select an option, and when the button is clicked, the selected options should download as a CSV file from my feeds. Below is th ...

Obtaining req.body twice while handling a 307 redirect in an Express application

I have encountered a unique issue with my form submission in an express js application. Upon form submission, data is being POST to another route and then redirected back to the original route. View <form action="action" method="post> <input t ...

JQuery implementation of Axis webservice call

Trying to invoke my Axis webservice with the code below var wsUrl = "http://localhost:8080/TestServ/services/TestCls?wsdl"; var soapreq = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cod=\"http:// ...

Problems with Vuex getter reactivity when used in conjunction with Vue router

I've encountered an issue with my Vuex getter that fetches data for the current route and displays it in a Vuetify v-data-table. Everything works perfectly fine when the component is initially created. However, when I add a new entry to the data array ...

Provide Chai/Mocha with a selection of essential keys that need to be incorporated

It appears that running the following code: describe( 'Add Youtube', function () { it( 'should return the video data, including user, title and content fields', function ( done ) { this.timeout( 5000 ) request({ ...

Arrange the table by column following a service request

Is there a method to organize the table below once it has been loaded? I am utilizing Google API to retrieve distance matrix data, but I want the table to be sorted by distance. However, this sorting should take place after the Google service call is comp ...

obtain information from a Java servlet on a web page

I am working on a webpage that displays various coordinates (longitude, latitude), and I need to create a Java class to sort these coordinates. My plan is to send the coordinates to a Java servlet before displaying them on the webpage. The servlet will th ...

What is the best way to move the Grid upward when the above content is not visible?

Let me demonstrate what I have been working on. Currently, I am creating a weather application to explore the functionalities of https://material-ui.com/. I am attempting to prototype an animation inspired by Google Flights, which can be seen here: https: ...

Enhancing Your Model with Additional Details using Angular Formly

I have been utilizing Angular Formly to display forms generated from the JSON response received from services. However, I have a few inquiries. Is it feasible to retrieve data in a field (templateOptions.label, for instance) to include in the model? ...

Utilize the Google Drive API to easily upload an Excel file

I'm encountering an issue with the Google Drive API. I've been attempting to upload an Excel file using this API, but haven't had any success. I even tried following the instructions in the Google API documentation without luck. Below is a ...

Unlocking Global Opportunities with Stencil for Internationalization

Hi there, I've been attempting to implement Internationalization in my stencil project but unfortunately, it's not working as expected. I'm not sure what's causing the issue, and all I'm seeing is a 404 error. I followed these arti ...