YasseMoh's avatar

CSRF token mismatch react laravel axios

i have an app with built with react and laravel. i tried authentication with laravel breeze. i get an error message(CSRF token mismatch). I need to solve that.

routes:

Route::group(['middleware'=>['web','guest']],function () {

    Route::post('login', [AuthenticatedSessionController::class, 'store']);
});

react:

import React, {useState,useRef } from 'react'
import { useNavigate } from 'react-router'
import axios from 'axios'
import './login.css'
  

const Login = () => {
    //values
    const [responseOk, setResponseOk] = useState()
    //navigate
    const navigate=useNavigate();
    //fields
    const refEmail = useRef('')
    const refPassword = useRef('')
    
    //submit ad
    const submitCheckUser=async(e)=>{
        e.preventDefault();
        //get values from form
        const email=refEmail.current.value.trim();
        const password=refPassword.current.value.trim();
        //show form error
      const showError=(field,value,ref)=>{
        if(field==value){ref.current.style.backgroundColor='#e87878';}else{ref.current.style.backgroundColor='white';}
      }
      
        //check if form values are valid
        showError(email,' ',refEmail);
        showError(password,' ',refPassword);
        //store values
        const postData={email,password}
        
        //send values to backend
        if(email!='' && password!='' ){
            try{
                const res= await axios.post('http://127.0.0.1:8000/api/login',postData,{
                    withCredentials: true,  
                    headers: { 'Content-Type': 'application/json'}
                });
                console.log(res.data)
            setResponseOk('values received')
           // navigate=('/');
            }catch (error) {
               console.error(error);
               
            setResponseOk('watch the errors')
            } //end catch
        }//end if
        

    }//end submitAddFunc

    return (
        <div className='container-fluid top-add'>
            
        <form onSubmit={submitCheckUser} className='w-50 mx-auto my-5 form-add b-radius-1'>
             <p className="w-fit mx-auto fw-bold fs-2">Login </p>
             
            <div className="mb-3 d-flex ">
                <label htmlFor="email" className="form-label">email</label>
                <input type="email"  ref={refEmail} className="form-control" id="email" placeholder="enter add title"/>
            </div>

            <div className="mb-3 d-flex ">
                <label htmlFor="password" className="form-label">password</label>
                <input type="password"  ref={refPassword} className="form-control" id="password" placeholder="enter add title"/>
                <i className='bi bi-eye'></i>
            </div>

            <button type="submit" className="btn btn-primary mx-auto w-fit d-block">Submit</button>
            {responseOk && (<p className="w-fit mx-auto mt-4 fw-bold">{responseOk}</p>) }              

        </form>

    </div>

    )
}

export default Login

controller:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(): View
    {
        return view('auth.login');
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request)//: RedirectResponse
    {
        $request->authenticate();

        $request->session()->regenerate();

       // return redirect()->intended(RouteServiceProvider::HOME);
        return response()->json('you were authenticated successfully');
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
}

0 likes
5 replies
jlrdw's avatar

Where are you sending the token from?

1 like
YasseMoh's avatar

@jlrdw from the form in the React component. By the way, i have the backend and the front end in separate folders

1 like
YasseMoh's avatar

@puklipo i have two separate folders (app/frontend) for React folders and (app/backend) for laravel folders. The login form is inside the React part. should I put react folders inside (app/backend/resources/js) so that it would be proper to get the CSRF token when I send the form from the React component?

1 like

Please or to participate in this conversation.