Skip to content
This repository has been archived by the owner on Sep 14, 2022. It is now read-only.

Failed on validation when using with 2 backends #255

Open
convers39 opened this issue Apr 19, 2022 · 0 comments
Open

Failed on validation when using with 2 backends #255

convers39 opened this issue Apr 19, 2022 · 0 comments

Comments

@convers39
Copy link

convers39 commented Apr 19, 2022

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?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants