reactjslaravel-passport

Laravel Passport auth api in Reactjs


How to setup API authentication in reactjs using laravel passport? Before this I'm using laravel sanctum, where we need to get csrf cookie first before logging in an user. But I'm did not managed to find tutorials on how to use laravel passport in reactjs.

This is what I've tried, but I got 404 error, where it doesn't capture the value of phoneNumber although I've keyed in the correct phoneNumber and password.

Feel free to share any references that are useful for me to auth api using laravel passport in reactjs.

  const [password, setPassword] = useState("");
  const [phoneNumber, setPhoneNumber] = useState("");
  const navigate = useNavigate();

// handle login
  const handleSubmit = async (event) => {
    event.preventDefault();
    const submitData = { phoneNumber, password };

    try {
      const response = await axios.post("http://localhost:8000/api/login", submitData, {
        headers: {
          "Content-Type": "application/json",
          "Custom-Header": "value",
        },
      });
      localStorage.setItem("token", response.data.token);
      navigate('/home');
    } catch (error) {
      console.log("Error: ", error);
    }
  };


<form
        className="pt-8 flex flex-col gap-4 px-6"
        onSubmit={(e) => handleSubmit(e)}
      >
<input
              type="text"
              name="phoneNumber"
              value={phoneNumber}
              onChange={(e) => setPhoneNumber(e.target.value)}
              className="bg-transparent placeholder:text-g50 text-g60 outline-none text-sm placeholder:text-sm"
              placeholder="0123456789"
            />

<input
              type={type}
              name="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="bg-transparent placeholder:text-g50 text-g60 outline-none text-sm placeholder:text-sm passwordField w-full pr-3"
            />

<button className="primaryButton w-full" type="submit">
            Log In
          </button>

Solution

  • Laravel password is not like sanctum (which I though it would be somewhat similar but no).

    You don't need to get csrf cookie, but need to setup a few codes for the login api. You'll need to add grant_type, client_id & client_secret and pass it as data in the url.

    const loginData = {
        grant_type: 'password',
        client_id: 'your_client_id',         // Replace with your client ID
        client_secret: 'your_client_secret', // Replace with your client secret
        username: email,               // The user's email
        password: password,
        scope: '',                           // Optional
      };
    
    try {
        const response = await axios.post('http://localhost:8000/oauth/token', loginData, {
          headers: {
            'Content-Type': 'application/json',
          },
        });
    

    Only login api needs that, the rest of api no need bcuz here is where access token is being generated.

    You maybe asking where to get the client_id & client_secret, that's in the laravel documentation (pls read)