I'm having a problem with csrf_token. I see the `c...
# talk-kratos
j
I'm having a problem with csrf_token. I see the
csrf_token
cookie is transmitted OK and I'm not attaching any
csrf_token
in the POST data:
Copy code
const onRegister = () => {
    return Kratos.completeSelfServiceRegistrationFlowWithPasswordMethodRaw(
      {
        flow: router.query.flow?.toString(),
        body: { password: "password", email: "<mailto:email@example.pl|email@example.pl>", name: { first: "first", last: "last" } }
      })
      .then(() => {
        console.log("OK")
      }).catch(e => console.error("ERROR", e))
  }
Kratos error
Copy code
level=error msg=An error occurred while handling a request audience=application error=map[debug: details:map[docs:<https://www.ory.sh/kratos/docs/debug/csrf> hint:The anti-CSRF cookie was found but the CSRF token was not included in the HTTP request body (csrf_token) nor in the HTTP Header (X-CSRF-Token). reject_reason:The HTTP Cookie Header was set and a CSRF token was sent but they do not match. We recommend deleting all cookies for this domain and retrying the flow.] message:the request was rejected to protect you from Cross-Site-Request-Forgery reason:The request was rejected to protect you from Cross-Site-Request-Forgery (CSRF) which could cause account takeover, leaking personal information, and other serious security issues. status:Forbidden status_code:403] http_request=map[headers:map[accept:*/* accept-encoding:gzip, deflate, br accept-language:en,pl;q=0.9,en-US;q=0.8 connection:keep-alive content-length:76 content-type:application/json cookie:csrf_token_82b119fa58a0a1cb6faa9738c1d0dbbf04fcc89a657b7beb31fcde400ced48ab=04yNxJpTkHv9VY0ChiMar1V0IX8vpt5XcPCzOHZS37c= origin:<http://localhost:3001> referer:<http://localhost:3001/> sec-ch-ua:" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97" sec-ch-ua-mobile:?0 sec-ch-ua-platform:"Linux" sec-fetch-dest:empty sec-fetch-mode:cors sec-fetch-site:same-site user-agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36] host:localhost:4433 method:POST path:/self-service/registration/methods/password query:flow=f4d1c01f-0f74-47d4-8d7b-a37e15404d3d remote:[::1]:43640 scheme:http] http_response=map[status_code:403] service_name=Ory Kratos service_version=v0.8.2-alpha.1
I'm generating ts-fetch client, credentials set to 'include', using next.js I just don't know how to set the
csrf_token
so it matches the cookie.
h
Long time no see, glad to see you around 🙂
Can you show how you init the SDK?
j
It's my n-th project with ory 😄 My only init code:
Copy code
let params: ConfigurationParameters = {
  basePath: "<http://localhost:4433>",
  credentials: 'include',
}

export default new PublicApi(new Configuration(params))
and it works, cookies are included
h
Ah, i believe your body does is missing the CSRF Token parameter
csrf_token: "..."
The SDK is not really good at echoing response errors but you can check
.catch(err => err.response.data)
for the full output. For CSRF errors, it should include a detailed explanation what's missing.
By the way, not sure if you're interested, but since you've been here since 2016 (? ^^) maybe you'd be interested in writing a small blog post how you've seen Ory evolve? ofc you can backlink to your company / project 🙂 @User would probably be quite excited to see such a story :)
j
And this csrf_token shoud be set to the cookie value?
h
In the first call where you have
init...
it returns a number of nodes in
ui.nodes
and one of them is a node with name "csrf_token". you have to use that one
j
initializeSelfServiceRegistrationViaBrowserFlowRaw
returns a redirection, there's no body with csrf_token inside.
Copy code
import { useRouter } from 'next/router'

...

  const onRegisterStart = () => {
    return Kratos.initializeSelfServiceRegistrationViaBrowserFlowRaw()
      .then(({ raw }) => {
        router.push(raw.url)
      }).catch(e => console.error(e))
  }
This redirects to the right URL with the flow id in query.
m
Would love to see the perspective of such a longtime user, if you are interested let me know Janek! We could e.g. do a short overview of what you built with Ory, I am gathering material for an open source showcase also.
I have the same problem with CSRF token in my react example at the moment @User 😞.
😅 1
h
@User sorry, in that case I meant when you get the flow, so
getSelfServiceRegistration...
j
Now I get it! I didn't even know that I should make this call :D
I see the
ui.nodes
in the response
h
ok nice 🙂
j
I'm still getting the same error. This is what happens when user clicks "Register" button:
Copy code
const onRegister = () => {
    return Kratos.getSelfServiceRegistrationFlowRaw({ id: router.query.flow?.toString() || "" })
      .then(r => r.raw.json())
      .then(r => {
        console.log("R", r.ui.nodes[0])
        console.log("V", r.ui.nodes[0].attributes.value)
        return Kratos.completeSelfServiceRegistrationFlowWithPasswordMethodRaw(
          {
            flow: router.query.flow?.toString(),
            body: {
              csrf_token: r.ui.nodes[0].attributes.value,
              password: "password", traits: { email: "<mailto:email@email.com|email@email.com>", name: { first: "fir", last: "las" } }
            }
          })
      })
      .then(() => {
        console.log("B")
      }).catch(e => console.error(e))
  }
I fear I oversimplify things. Can body be passed as JSON like this?
I think fallowing this example will solve all my problems: https://github.com/ory/kratos-selfservice-ui-react-nextjs Thanks
🙏 1
d
@User Did you manage to resolve this? We have a similar issue.
j
Not yet, although I'm pretty sure that the problem lies in the format of the data that gets sent. Kratos seems to use content-type header and expect form data
@User I think csrf_token related problems deserve a separate channel on slack :D
h
haha yeah…i don't know how to improve the docs, so you have an idea?
*do
j
My only problem is that I don't really know: • if the crsf_token and cookie should be the same • should I encode data like a form or json
And the flows do not contain the names of the functions that need to be called. That would save you a lot of explaining :D
But honestly the amount of doc available on Ory's site is really impressive
🙌 1
h
And the flows do not contain the names of the functions that need to be called. That would save you a lot of explaining :D
could you elaborate? :)
d
happy to help on the docs once we figure this out 🤷‍♂️ . We seem to be struggling. We’re now at the point where we have the cookie being set in the browser by redirecting to http://127.0.0.1:4433/self-service/registration/browser, but we’re struggling to send it through to the 
getSelfServiceRegistrationFlow
 in our Vue app to fetch the registration form data.
j
h
ah got it! we'll be soon adding some proper sdk examples..
so not like heres how the flow works
but rather heres a guide to implement the login screen