Laravel 403 之前有效的 API 错误

问题描述 投票:0回答:5

截至昨天,下面的代码有效。然而今天,我必须在 laravel 中运行 php artisan config:cache 命令,因为我添加了一个包,现在我漂亮的 ionic 应用程序不想运行连接到任何东西,因为我不断收到此 403 错误。

在我安装“rap2hpoutre/laravel-log-viewer”:“^0.19.1”并缓存后开始出现错误,但我认为这与它没有任何关系。我很确定我的缓存在此之前是最新的。

jwt 会产生相同的错误。

以前,该应用程序无需 cors 插件即可运行。

它在本地和我的服务器上向我提供了此错误(因为我也必须在那里缓存)。

这个错误与我之前调试时遇到的错误不同。

当我拉出路线 http://xxx/api/home 通常在 chrome 中 - 它返回正常...在邮递员中也一样

感谢您的帮助!

错误

选项 http://xxx/api/home 403(禁止) 无法加载 http://xxx/api/home:预检响应没有 HTTP 正常状态。

离子

basicGet_no_token(rl){
        console.log('basicGet - ' + this.base_url + rl);
        return new Promise((resolve, reject) => {
            this.http.get(this.base_url + rl, 
                {headers: new HttpHeaders({
                    'Content': 'application/json',
                    'Accept': 'application/json',
                })})
                .subscribe(res => {console.log(res);resolve(res);}, (err) => {this.handleError(err);console.log(err);reject(err);});
        }); 
    }

拉拉维尔

Route::group(['middleware' => ['addHeaders']], function () {
    Route::get('home', 'api\WelcomeController@home');
});

class addHeaders
{
    public function handle($request, Closure $next)
    {
    if ($request->getMethod() == "OPTIONS") {
      return response(['OK'], 200)
        ->withHeaders([
          'Access-Control-Allow-Origin' => '*',
          'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE',
          'Access-Control-Allow-Credentials' => true,   
          'Access-Control-Allow-Headers' => 'Origin, Content-Type, X-Auth-Token, authorization, X-Requested-With'
        ]);
    }

    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
        ->header('Access-Control-Allow-Credentials', true)
        ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token, authorization, X-Requested-With');

    }
}

class WelcomeController extends Controller
{
  public function home()
  {
        $r['message']="Welcome!";
    $r['allow']=true;
    $p=compact('r');
    return response()->json($p, 200);
  }
}


class Kernel extends HttpKernel
{

    protected $middlewareGroups = [
          'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    protected $routeMiddleware = [
        'auth'      => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic'  => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings'    => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can'       => \Illuminate\Auth\Middleware\Authorize::class,
        'guest'     => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'jwt'           => \App\Http\Middleware\JWT::class,
        'addHeaders'    => \App\Http\Middleware\addHeaders::class,
      'jwt.auth'    => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
      'jwt.refresh'   => \Tymon\JWTAuth\Middleware\RefreshToken::class,        
        'throttle'    => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}
php laravel ionic-framework cors wampserver
5个回答
11
投票

这个答案可能不适合所有人,但如果您创建了自定义请求并忘记授权方法返回 true,您可能会遇到此错误。

我正在处理策略授权,经常忘记请求验证。创建自定义请求时请仔细检查

注意:另请注意,如果您正在使用策略,您可能会忘记在

AuthServiceProvider

中将策略建模的映射

4
投票

如一开始所述,您正在使用缓存 - 至少其中一个用于

config

有些包与 Laravel 的缓存机制不能很好地配合,有时你只是忘记你正在使用任何缓存 - 你应该永远记住这一点!

因此,不要在开发中使用任何缓存(这是我个人的偏好,以免为不存在的问题浪费时间)。

在生产中,在部署时,您需要确保自己绝对确定所有缓存都会被重新创建。

这些功能对你来说可能有点困难:

php artisan cache:clear

php artisan route:clear

php artisan config:clear

php artisan view:clear

所以请检查一下...


0
投票

我能够找到我的配置的备份副本并恢复它。


0
投票

尝试请求安全 URL,例如; HTTPS://xxxx.yy/端点

API 通常需要使用 HTTPS 的请求。如果你使用 POSTMAN,你应该确定它。

享受编码的乐趣!


0
投票

出现 403 Forbidden 错误是因为 Request 类中的授权方法返回 false。该方法用于确定用户是否有权发出请求。默认情况下。

要解决此问题,需要修改authorize方法以返回true

听到的是文档

<?php

命名空间 App\Http\Requests;

使用 Illuminate\Foundation\Http\FormRequest;

类 StoreCustomerRequest 扩展了 FormRequest { /** * 确定用户是否有权提出此请求。 */ 公共函数authorize(): bool { 返回真; //默认情况下这是 false }

/**
 * Get the validation rules that apply to the request.
 *
 * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
 */
public function rules()
{
    return [
        'customer_name' => 'required|string|max:255',
        'company' => 'required|string|max:255',
        'email' => 'required|email|max:255',
        'country' => 'required|string|max:255',
        'firstAddress' => 'required|string|max:255',
        'secondAddress' => 'nullable|string|max:255',
    ];
}

}

© www.soinside.com 2019 - 2024. All rights reserved.