使用react native与laravel breeze的令牌不匹配

k4ymrczo  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(99)

我正在尝试将一个react项目转换为react native,但在身份验证方面遇到了问题。后端是Laravel,带有Breeze工具包来提供身份验证。我设法从laravel-sanctum获得令牌,方法是根据Laravel文档添加一个到API的路由,用于验证移动的应用程序。

Route::post('/sanctum/token', function (Request $request) {
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
        'device_name' => 'required',
    ]);

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

    if(!$user || !Hash::check($request->password, $user->password)) {
        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect'],
        ]);
    }

    return $user->createToken($request->device_name)->plainTextToken;
});

然后我点击后,以这条路线与登录细节

try {
    const response = await axios.post('http://192.168.1.105:8000/api/sanctum/token', {
        email: email,
        password: password,
        device_name: 'mobile',
    });

    const csrfToken = response.data;
    axios.defaults.headers.common['X-XSRF-TOKEN'] = csrfToken;
} catch (error) {
    console.log(error);
    Alert.alert('Login Failed', 'Please check your credentials and try again.');
}

我可以在响应中看到标记,所以这部分看起来不错。
然后我在客户端上创建了一个注销操作

const response = await axios.post('http://192.168.1.105:8000/logout', {});

我可以看到X-XSRF-TOKEN和XSRF-TOKEN cookie包含在标头中,但我得到了一个令牌不匹配错误。如果标准的“注销”路由不是为移动的应用程序设计的,我还尝试在后端创建一个新的注销路由。

Route::middleware('auth:sanctum')->group(function () {
    Route::post('/sanctum/logout', [AuthenticatedSessionController::class, 'logout']);
});

现在我得到unauthenticated。我的.env有APP_URL=192.168.1.105:8000,而sanctum.php有

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1, 192.168.1.105:3000, 192.168.1.105:8000',
    Sanctum::currentApplicationUrlWithPort()
))),

这两个通常解决问题,我有当我得到'未经认证'从SPA,但他们没有帮助在这里。我不知道还能尝试什么。

zhte4eai

zhte4eai1#

我错过了Laravel Sanctum文档中的一行,上面写着When the mobile application uses the token to make an API request to your application, it should pass the token in the Authorization header as a Bearer token.
经过一番调查,我发现我需要改变

axios.defaults.headers.common['X-XSRF-TOKEN'] = csrfToken;

axios.defaults.headers.common['Authorization'] = `Bearer ${csrfToken}`;

在做了这个改变之后,laravel识别了这个会话。

相关问题