问题
I have created REST API in AdoniJs. In this I have created API endpoints for CRUD operations with GET, POST, PUT and DELETE menthods. I am using shieldjs
as a middleware to verify CSRF
token. I am making API calls from Postman.
Firstly I am calling GET method of API and I am getting the expected data properly and 3 cookies as part of response, out of which, one is XSRF-TOKEN
.
But when I am calling PUT, POST and DELETE methods by setting key X-XSRF-TOKEN
to the value of XSRF-TOKEN
from the cookie in request header, I am getting error EBADCSRFTOKEN
as response in Postman.
Configuration of CSRF
in ShieldJS in shield.js
file
csrf: {
enable: true,
methods: ['POST', 'PUT', 'DELETE'],
filterUris: [],
cookieOptions: {
httpOnly: false,
sameSite: true,
path: '/',
maxAge: 7200
}
}
Code of Error Handler in handler.js
file
async handle (error, {request, response }) {
if (error.code === 'EBADCSRFTOKEN') {
response.forbidden(error.code)
return
}
}
When I am changing value of enable: false
for csrf
in ShieldJs then its working fine but after I do enable: true
I am getting the error EBADCSRFTOKEN
.
I should not get this error code as I am sending xsrf
token.
回答1:
Put filterUris in your route path like this
csrf: {
enable: true,
methods: ['POST', 'PUT', 'DELETE'],
filterUris: ['/firstroute','*',],
cookieOptions: {
httpOnly: false,
sameSite: true,
path: '/',
maxAge: 7200
}
}
More read about csrf visit this website adonisjs
Second way is
- Create REST API project. when creating API then not need a view. This error generates when not getting csrftoken.
So you can try to create a project for the only API not include view like this
adonis new projectname --api-only
More info follow this link how to create an API project.
来源:https://stackoverflow.com/questions/57452122/adonisjs-error-code-ebadcsrftoken-in-postman-in-put-post-delete-operation