Home > OS >  Authenticate my ReactJS SPA with laravel/sanctum using Axios
Authenticate my ReactJS SPA with laravel/sanctum using Axios

Time:03-11

After a successful authentication (login token), I'm still unable to request auth:sanctum routes and I get the following response:

enter image description here

Docs

... This token should then be passed in an X-XSRF-TOKEN header on subsequent requests, which some HTTP client libraries like Axios and the Angular HttpClient will do automatically for you.



Code


LoginForm component

import React, { useState } from "react";

const LoginForm = () => {
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    const loginHandler = (ev) => {
        ev.preventDefault();

        if (email.length > 0 && password.length > 0) {
            axios.get("/sanctum/csrf-cookie").then(() => {
                axios
                    .post("api/login", {
                        email: email,
                        password: password,
                    })
                    .then((response) => {
                        console.log(response.data);

                    })
                    .catch(function (error) {
                        console.error(error);
                    });
            });
        }
    };
    return (
        <form onSubmit={loginHandler}>
            <input
                type="email" value={email}
                onChange={(ev) => {
                    setEmail(ev.target.value.toLocaleLowerCase());
                }}
            />
            <input
                type="password" autoComplete="" value={password}
                onChange={(ev) => {
                    setPassword(ev.target.value);
                }}
            />

            <button> Connect </button>
        </form>
    );
};
export default LoginForm;

Login action

    public function login(Request $request)
    {
        $request->validate(['email' => 'required', 'password' => 'required|string']);

        $user = User::where('email', $request->email)->first();

        if (!$user || !password_verify($request->password, $user->password)) {
            return response(['message' => 'Bad credentials'], 401);
        }

        $token = $user->createToken('token')->plainTextToken;

        return response(['user' => $user, 'token' => $token], 201);
    }

Login Response

{
    "user": {
        "id": 7,
        "email": "[email protected]",
        "email_verified_at": "2022-03-09T16:40:59.000000Z",
        "created_at": "2022-03-09T16:40:59.000000Z",
        "updated_at": "2022-03-09T16:40:59.000000Z"
    },
    "token": "5|oCnoaVBBYARcFXwdd7dXegchFLS6fckDgr2Bl0L0"
}

CodePudding user response:

You need to pass Sanctum Token in Axios Header.

    first you need to set user response in local storage.
    
        const LoginForm = () => {
            const [email, setEmail] = useState("");
            const [password, setPassword] = useState("");
        
            const loginHandler = (ev) => {
                ev.preventDefault();
        
                if (email.length > 0 && password.length > 0) {
                    axios.get("/sanctum/csrf-cookie").then(() => {
                        axios
                            .post("api/login", {
                                email: email,
                                password: password,
                            })
                            .then((response) => {
                                 //set response in local storage
                                 localStorage.setItem('user', JSON.stringify(response.data))
                            })
                            .catch(function (error) {
                                console.error(error);
                            });
                    });
                }
            };

then you need to pass token in Axios Header

   const user = JSON.parse(localStorage.getItem('user'));
   const headers = {
        accept: 'application/json',
        Authorization: 'bearer '   user.token
    }

   //set token in axios header
   axios.get(API, {
       headers: headers
   })
    .then((res) => { })
    .catch((err) => { })
  • Related