From 7819ad0bad227f0a3f67cb68bba549292a4debf2 Mon Sep 17 00:00:00 2001 From: Christian Georgi Date: Tue, 30 Aug 2022 18:16:29 +0200 Subject: [PATCH] Support csrf tokens in Vue app --- bookshop/app/vue/app.js | 24 +++++++++++++++++++++++- fiori/app/_router/xs-app.json | 3 +-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/bookshop/app/vue/app.js b/bookshop/app/vue/app.js index 18e4ef23..b637d115 100644 --- a/bookshop/app/vue/app.js +++ b/bookshop/app/vue/app.js @@ -56,7 +56,7 @@ const books = Vue.createApp ({ } catch (err) { books.user = { id: err.message } } }, } -}).mount("#app") +}).mount('#app') books.getUserInfo() books.fetch() // initially fill list of books @@ -65,3 +65,25 @@ document.addEventListener('keydown', (event) => { // hide user info on request if (event.key === 'u') books.user = undefined }) + +axios.interceptors.request.use(csrfToken) +function csrfToken (request) { + if (request.method === 'head' || request.method === 'get') return request + if ('csrfToken' in document) { + request.headers['x-csrf-token'] = document.csrfToken + return request + } + return fetchToken().then(token => { + document.csrfToken = token + request.headers['x-csrf-token'] = document.csrfToken + return request + }).catch(_ => { + document.csrfToken = null // set mark to not try again + return request + }) + + function fetchToken() { + return axios.get('/', { headers: { 'x-csrf-token': 'fetch' } }) + .then(res => res.headers['x-csrf-token']) + } +} \ No newline at end of file diff --git a/fiori/app/_router/xs-app.json b/fiori/app/_router/xs-app.json index ea603849..ff255b9a 100644 --- a/fiori/app/_router/xs-app.json +++ b/fiori/app/_router/xs-app.json @@ -17,8 +17,7 @@ "source": "^/(.*)$", "target": "$1", "destination": "srv-api", - "authenticationType": "xsuaa", - "csrfProtection": false + "authenticationType": "xsuaa" } ] } \ No newline at end of file