首页 > 解决方案 > 尝试访问 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,
        ],
    ],

邮递员检查登录用户: 检查登录用户

邮递员试图获取登录用户的应用程序:

尝试获取已登录用户的应用程序会出错

标签: reactjslaravelreduxjwt

解决方案


我发现出了什么问题。实际上它不是我的代码,而是 linode 服务器上的 apache 配置。我在 apache 配置文件中添加了授权标头,它起作用了。


推荐阅读