reactjs - 尝试访问 JWT Authenticated Users 内容在 laravel 中给出 401
问题描述
我有 React 前端和 Laravel 后端应用程序,它们使用 JWT 对用户进行身份验证。登录过程正常,我可以使用 JWT 的 me 功能获取经过身份验证的用户。但是现在当我尝试基于经过身份验证的用户访问内容时,我收到 401 错误。我正在添加我的 react axios 函数以及我的 laravel 控制器,该控制器具有给出错误的函数。请指出我做错了什么。很感谢任何形式的帮助。谢谢你。
反应 axios 功能:
export const fetchMyApplications = () => {
return async dispatch => {
const url = `/auth/my-applications`;
var formdata = new FormData();
const token = getCookie("userToken");
const response = await api
.get(
url,
{
headers: {
Authorization: `Bearer ${token}`
}
}
)
.then(res => {
return res;
})
.catch(error => {
return error.response;
});
dispatch({
type: "FETCH_MY_APLICATIONS",
payload: response
});
};
}
Laravel 控制器:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Models\Application;
class ApplyController extends Controller
{
public function __construct()
{
\Config::set('auth.providers.users.model', \App\Applicant::class);
$this->middleware('auth:api', ['except' =['personalDetails']]);
}
public function myApplications(){
try {
$user = auth()->userOrFail();
$applications = Application::where('applicant_id', $user->applicant_id)->with('course')->get();
return response()->json(['applications'=> $applications], 200);
}catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
return response()->json(['status'=> false, 'errors'=> 'Unauthenticated User'], 401);
}
}
}
授权配置:
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
邮递员试图获取登录用户的应用程序:
解决方案
我发现出了什么问题。实际上它不是我的代码,而是 linode 服务器上的 apache 配置。我在 apache 配置文件中添加了授权标头,它起作用了。
推荐阅读
- sitefinity - 在本地计算机上恢复其数据库副本时无法登录到 sitefinity 后端
- c# - 有没有办法使用 vsto c# 选择刚刚粘贴到 word 文档中的表对象
- python - 如何在没有硒的情况下从 aspx 页面中分页和抓取数据
- ruby - 更改 Sinatra 视图目录位置
- django - save() 函数中的 Django 消息传递框架
- python-3.x - ValueError:传递值的形状为 (1027, 8),索引暗示 (1030, 8)
- kotlin - Kotlin @Composable 调用只能在 @Composable 函数的上下文中发生
- angular - 按 ID 的角度路由
- php - Wordpress How to change date format for _get_last_post_time function
- ios - SwiftUI:将 List 放入 ScrollView(获取 List 的内容高度)