简体   繁体   中英

Laravel csrf token mismatch for axios post request

I am have been very desperate for these few days because I seem can't overcome this one simple problem.

I can not authenticate my SPA (react via Axios) powered by Sanctum Laravel

I have read the documentation and read man tutorials and questions. Some problems have I overcome.

Eventually, I stuck in this one:

My request has contained the X-CSRF-TOKEN, but it always returns a 419 "message: CSRF token mismatch."

Here is my error details:

Here is my cors.php

    <?php

return [

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

];

Here is App.js from react app

    import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import Login from './components/auth/login';
import Register from './components/auth/register';

import axios from 'axios';

axios.defaults.baseURL = 'http://127.0.0.1:8000/';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.post['Accept'] = 'application/json';
axios.defaults.withCredentials = true;

function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path="/login" element={<Login />} />
          <Route path='/register' element={<Register />}></Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;

Here is the register.js

    import React, { useState } from "react";
import axios from "axios";

import '../../css/login2.css'
import '../../css/login3.css'

function Register() {

    const [register, setRegister] = useState({
        email: '',
        password: '',
        confirmPassword: ''
    });

    const handleInput = (e) => {
        e.persist();
        setRegister({
            ...register,
            [e.target.name]: e.target.value
        })
    }

    const submit = (e) => {
        e.preventDefault();
        const data = {
            email: register.email,
            password: register.password,
            confirmPassword: register.confirmPassword
        }
        axios.get('/sanctum/csrf-cookie').then(response => {
            console.log(response);
            axios.post('/api/register', data).then(res => {
                console.log("res: "+res);
            }).catch(err => {
                console.log("err"+err);
            })
        })
    }

    return (
        <section className="section-register d-flex justify-content-center align-items-center">
            <div className="box" style={{ width: "20rem", }}>
                <h3 className="text-center font-weight-bold mb-4">Register</h3>
                <form onSubmit={submit}>
                    <div className="form-group">
                        <input type="email" onChange={handleInput} className="form-control" placeholder="Email Address"
                            name="email" />
                    </div>
                    <div className="form-group">
                        <input type="password" onChange={handleInput} className="form-control"
                            placeholder="Password" name="password" />
                    </div>
                    <div className="form-group">
                        <input type="password" onChange={handleInput} className="form-control"
                            placeholder="Confirm Password" name="password_confirmation" />
                    </div>
                    <div className="form-group">
                        <button type="submit" className="btn btn-primary btn-block btn-rounded">Continue</button>
                    </div>
                </form>
                <div className="or mt-4 mb-4">
                    <span className="">OR</span>
                </div>
                <div className="text-center">
                    <a href="/login" className="btn btn-outline-primary btn-rounded clever"
                        style={{ textDecoration: "none !important", }}>Login</a>
                </div>
            </div>
        </section>
    );
}

export default Register;

try to enable csrf token in your middlewareGroups array at app/http/kanel.php file, and also enable EnsureFrontendRequestsAreStateful in the api array below it. and then add this header configuration to you axios request

const serverUrl = http://localhost:8000 ;

const http = axios.create({ baseURL: serverUrl, headers: { "X-Requested-with": "XMLHttpRequest", }, withCredentials: true, });

or simply try to follow the steeps in this article that was how i solved mine.

https://dev.to/dog_smile_factory/authenticating-a-react-app-with-laravel-sanctum-part-1-44hl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM