AdonisJS Error Code “EBADCSRFTOKEN” in Postman in PUT,POST,DELETE operation

倖福魔咒の 提交于 2019-12-10 10:36:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!