csurf icon indicating copy to clipboard operation
csurf copied to clipboard

Failed on validation when using with 2 backends

Open convers39 opened this issue 2 years ago • 0 comments

I have 2 different nodejs backends which both use csurf to issue csrf tokens. But only one is working properly.

The codes are very identical, both api/auth and api/reviews are getting called during page loading, but only csrf_1 appears in the cookies.

// backend A
require('dotenv').config()

const app = express()

app.use(cors({ origin: ALLOWED_ORIGINS, credentials: true }))
app.use(express.json())
app.use(cookieParser())

app.use(csrf({ cookie: {key: '_csrf_1'} }))
app.use('/api/auth', authRouter)

// call this api to get csrfToken
app.get('/api/auth/csrf', function (req, res) {
  const token = req.csrfToken()
  // console.log(`CSRF-TOKEN:${token}`)
  res.json({csrfToken: token})
})
// backend B
require('dotenv').config()

const app = express()

app.use(cors({ origin: ALLOWED_ORIGINS, credentials: true }))
app.use(express.json())
app.use(cookieParser())

app.use(csrf({ cookie: {key: '_csrf_2'} }))
app.use('/api/reviews', reviewRouter)

// call this api to get csrfToken
app.get('/api/auth/csrf', function (req, res) {
  const token = req.csrfToken()
  // console.log(`CSRF-TOKEN:${token}`)
  res.json({csrfToken: token})
})

image

From the react front end I call /api/auth/csrf first before I send a post request, and set the token to the header.

          const res = await axios.get(
            `${...}/api/auth/csrf`,
            {
              withCredentials: true
            }
          )
          axios.defaults.headers.post['X-CSRF-TOKEN'] = res.data.csrfToken

Only backend A is successful on validation, backend B somehow didn't attach the token to the cookie and failed on validation.

What am I missing here? Are there any better practices when dealing with multiple backends with the same frontend?

convers39 avatar Apr 19 '22 07:04 convers39