Giter VIP home page Giter VIP logo

Comments (6)

grahamsutton avatar grahamsutton commented on August 30, 2024 4

To make a POST request with CSRF protection while using the shopify.auth middleware, you need to do the following:

In web/config/session.php

return [
    'secure' => true,
    'same_site' => 'none'
];

Add a route in your routes/web.php file to generate a CSRF token:

web/routes/web.php

Route::get('/api/csrf-token', fn () => ['csrf_token' => csrf_token()]);

Create a hook for fetching the CSRF token:

web/frontend/hooks/useCsrf.js

import { useAuthenticatedFetch } from './useAuthenticatedFetch'

/**
 * A hook for fetching a CSRF token from the server.
 *
 * The CSRF token MUST be included in every POST, PUT, PATCH, or DELETE
 * request sent to the server as a property called "_token" in the JSON body
 * or by header as X-CSRF-TOKEN.
 *
 * @returns {Function}
 */
export const useCsrf = () => {
  const fetch = useAuthenticatedFetch()

  return async () => {
    const response = await fetch('/api/csrf-token')
    const { csrf_token } = await response.json()

    return csrf_token
  }
}

Then, when submitting a non-GET request, fetch it before submitting the form, for example:

import { Form } from '@shopify/polaris'
import { useAuthenticatedFetch } from '../../hooks/useAuthenticatedFetch'
import { useCsrf } from '../../hooks/useCsrf'

export default function MyComponent() {
  const fetch = useAuthenticatedFetch()
  const csrf = useCsrf()

  const handleSubmit = async formValues => {
    const csrfToken = await csrf()

    const response = await fetch('/api/somewhere', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': csrfToken  // Include as header
      },
      body: JSON.stringify({
        _token: csrfToken    // OR include as "_token" property on the body, either works
        ...formValues
      })
    })
  }

  return (
    <Form onSubmit={handleSubmit}>
      {/* form contents */}
    </Form>
  )
}

With the hook, you can now easily include CSRF protection on all forms in your React frontend.

Because the React frontend and Laravel backend have different origins, the default 'same_site' => 'lax' in config/session.php prevents cookies from being correctly set in the browser. Setting this to 'none' allows the cookies to be set. Setting 'secure' to true also ensures the cookies are only set over HTTPS. Once you've changed those values, you should be able to see your session cookie stored in the browser. Without the session cookie, the Laravel backend will regenerate a CSRF token on every request and you will always end up getting a CSRF token mismatch error.

TIP: Always include the 'Content-Type': 'application/json' header when making a POST request or your Laravel's request body will be empty.

from shopify-app-template-php.

nemwiper avatar nemwiper commented on August 30, 2024 1

@galtechstaffs I have the same issue. Is there someone who has already fixed this??? @shopify-admins

I ended up putting an exception in the VeryfyCsfrToken file for the routes and using the "useAuthenticatedFetch" hook to make the calls.

from shopify-app-template-php.

amitappaspect avatar amitappaspect commented on August 30, 2024 1

Yes @nemwiper , useAuthenticatedFetch is worked fine.

from shopify-app-template-php.

github-actions avatar github-actions commented on August 30, 2024

This issue is stale because it has been open for 60 days with no activity. It will be closed if no further action occurs in 14 days.

from shopify-app-template-php.

github-actions avatar github-actions commented on August 30, 2024

We are closing this issue because it has been inactive for a few months.
This probably means that it is not reproducible or it has been fixed in a newer version.
If it’s an enhancement and hasn’t been taken on since it was submitted, then it seems other issues have taken priority.

If you still encounter this issue with the latest version of this template, please reopen using the issue template. You can also contribute directly by submitting a pull request

Thank you!

from shopify-app-template-php.

amitappaspect avatar amitappaspect commented on August 30, 2024

@galtechstaffs I have the same issue. Is there someone who has already fixed this??? @shopify-admins

from shopify-app-template-php.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.