#Where should I set antiCSRFToken to call Blitz API with external app

1 messages · Page 1 of 1 (latest)

willow bone
#

Hello, I need an API for my Blitz app. I can't quite figure out this tutorial: https://blitzjs.com/docs/session-management#manual-api-requests

Where exactly should I set antiCSRFToken? What is the variable "header"? External apps should be able to send an arbitrary string to a backend route of my app without authentication.

I created a file "app/core/mutations/myRequest.ts" with this content:

`import { resolver } from "@blitzjs/rpc"
import { Ctx } from "blitz".

export default resolver.pipe(
async (request: string, ctx: Ctx) => {
await processRequest(request)
return { status: "done" }
}
)`

However, when I send a post request to http://localhost:3000/api/rpc/myRequest with postman I get this error:

{ "name": "CSRFTokenMismatchError", "statusCode": 401 }

upbeat verge
willow bone
upbeat verge
#

Aj sorry. Si you create a csrf token first and then you send it in the header: anti-csrf

#

Does that make sense?

willow bone
upbeat verge
#

Depends, how are you calling your api.

willow bone
#

I'm using a blitz mutation as described in the example in my question.

upbeat verge
#

With curl it would be with a flag - H

willow bone
#

Do you mean I have to generate an antiCSRFToken with getAntiCSRFToken(), console.log it and that set it in my curl request?

#

If I execute the getAntiCSRFToken message in my mutation I get a ReferenceError: localStorage is not defined

upbeat verge
#

The token is generated on server side. So it should not give this message

willow bone
upbeat verge
#

Easy answer would be don't check Auth.

willow bone
#

Ok, it can be disabled with DANGEROUSLY_DISABLE_CSRF_PROTECTION=true for all routes. But it doesn't feel like the correct way. Do I have to disable csrf protection to enable external applications to call my api?

willow bone
upbeat verge
# willow bone How do I do that?

a simple api endpoint?

import db from "db"
import { NextApiRequest, NextApiResponse } from "next"

const apiEndpointFunction = async (req: NextApiRequest, res: NextApiResponse) => {
  
const someId: number = parseInt(req.query.someId as string)
  if (!someId) {
    res.json({ msg: "missing someId" })
  }
  res.status(200).json({msg:"hello"})
}

export default apiEndpointFunction

place it in pages/api/myEndpoint.ts