如何使用 Laravel Passport 在 ReactJS 中设置 API 身份验证?在此之前,我使用 laravel sainttum,在登录用户之前我们需要先获取 csrf cookie。但我没有找到有关如何在 ReactJS 中使用 Laravel Passport 的教程。
这是我尝试过的,但我收到了 404 错误,尽管我输入了正确的电话号码和密码,但它没有捕获电话号码的值。
请随意分享任何对我在 ReactJS 中使用 Laravel Passport 验证 api 有用的参考资料。
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>
Laravel 密码不像 圣所(我认为它会有点相似,但事实并非如此)。
您不需要获取csrf cookie,但需要为登录api设置一些代码。您需要添加 grant_type、client_id 和 client_secret 并将其作为数据传递到 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',
},
});
只有登录 api 需要,其余 api 不需要 bcuz 这里是生成访问令牌的地方。
您可能会问从哪里获取 client_id 和 client_secret,这在 laravel 文档中(请阅读)