Laravel & VueJS CORS 尝试对用户进行身份验证时出现问题,即使使用 Cors 中间件也是如此

Posted

技术标签:

【中文标题】Laravel & VueJS CORS 尝试对用户进行身份验证时出现问题,即使使用 Cors 中间件也是如此【英文标题】:Laravel & VueJS CORS Issue when trying to authenticate the user, even with the Cors middleware 【发布时间】:2020-09-21 19:55:48 【问题描述】:

我正在尝试为我的项目创建一个身份验证网关,但我不断收到这样的 cors 错误:

cors error in browser console

我使用 Laravel 作为网关,使用 Vue.js 作为前端。我制作了一个 cors 中间件,如 this video

所示

这是我在 Laravel 中的登录功能

public function login(Request $request)
    $loginCreds = $request->validate([
       'email' => 'required|string',
       'password' => 'required|string'
    ]);

    if(!auth()->attempt( $loginCreds ))
        return response()->json(['message'=>'Invalid login credentials.']);
    

    $at = auth()->user()->createToken('authToken')->accessToken;

    return response()->json(['user'=>Auth::user(), 'access_token' => $at]);

这是我从前端打的电话

        submitLogin() 
            let params = new URLSearchParams();
            params.append('email', this.email);
            params.append('password', this.password);
            axios(
                method: 'post',
                url: 'http://localhost:3000/api/auth/login',
                data: params
            )
                .then(res => 
                    console.log(res);
                ).catch(err => console.log(err));
        

该设置给了我错误,但如果我进行相同的调用但我的登录功能中有以下内容,它不会给我错误

public function login(Request $request)

    return \GuzzleHttp\json_encode('ok');

我不知道该怎么做,感谢任何帮助,提前谢谢!

[编辑]

我的 Cors 中间件

namespace App\Http\Middleware;

use Closure;

class Cors

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    
        header("Access-Control-Allow-Origin: *");
        //ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,PUT,DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization',
        ];
        if ($request->getMethod() == "OPTIONS")
            //The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return response()->json('OK',200,$headers);
        
        $response = $next($request);
        foreach ($headers as $key => $value) 
            $response->header($key, $value);
        
        return $response;
    

还有Kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel

    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\Cors::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    ];

我使用 Laravel v7.14.1 和 Laravel Passport 进行身份验证

【问题讨论】:

嗨,你能分享你的 CORS 中间件吗,你 app/Http/kernel.php @FouedMOUSSI 我在问题中添加了它 检查我的更新答案 编辑成功,谢谢!!! 【参考方案1】:

[编辑]

尝试更新app/Http/Middleware/Cors.php中返回的标头

<?php
namespace App\Http\Middleware;
use Closure;
class Cors

   public function handle($request, Closure $next)
   
     return $next($request)
       ->header(‘Access-Control-Allow-Origin’, ‘*’)
       ->header(‘Access-Control-Allow-Methods’, ‘GET, POST, PUT, DELETE, OPTIONS’)
       ->header(‘Access-Control-Allow-Headers’, ‘X-Requested-With, Content-Type, X-Token-Auth, Authorization’);
   

来源:Medium

[替代]

我用的是fruitcake/laravel-cors包,你可以试试

设置步骤

1.安装

在您的 composer.json 中需要 fruitcake/laravel-cors 包并更新您的依赖项:

composer require fruitcake/laravel-cors

2。发布配置

发布配置以将文件复制到您自己的配置:config/cors.php

php artisan vendor:publish --tag="cors"

3.用法

3.1 全球使用

要允许所有路由使用 CORS,请在 app/Http/Kernel.php 类的 $middleware 属性中添加 HandleCors 中间件:

protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];
3.2 仅适用于 API 路由使用

要允许您的 API 路由使用 CORS,请在 app/Http/Kernel.php 类的 $middlewareGroups 属性中添加 HandleCors 中间件:

protected $middlewareGroups = [
     'web' => [
          // ...
     ],

     'api' => [
          // ...
          \Fruitcake\Cors\HandleCors::class,
     ],
];

回购link

希望对你有帮助

【讨论】:

无法安装包,composer给我报错

以上是关于Laravel & VueJS CORS 尝试对用户进行身份验证时出现问题,即使使用 Cors 中间件也是如此的主要内容,如果未能解决你的问题,请参考以下文章

被 CORS 政策阻止并没有解决! Laravel + Vuejs

错误:laravel/VueJS ajax 请求中的 CORS

Laravel VueJS,Axios 看不到 CORS 标头,但 Postman 和浏览器可以

VueJs Axios Access-Control-Allow-Origin CORS 错误

如何解决 cors 在 vue js 和 laravel 应用程序中允许访问控制

Laravel & VueJS 变量定义