You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure VPC部署Laravel应用POST请求报错:XSRF-TOKEN域名无效

Azure部署Laravel应用的XSRF-TOKEN Cookie问题

我在Azure VPC中部署了Laravel应用(包含Azure Web App和Azure MySQL Flexible Server),发起POST请求时遇到错误。虽然已在Azure面板配置环境变量,但开发者工具提示:"XSRF-TOKEN Cookie因域名无效被拒绝"。

疑问

  • 是否需要修改session.php中的设置?
  • 是否需要添加其他环境变量?

应用在自有域名的HTTPS环境下可正常运行,但登录请求被拒绝。我添加了日志功能,发现请求直接被拦截,未返回预期错误信息。

补充信息

浏览器提示连接不安全,怀疑是表单路由使用HTTP而非HTTPS导致。我尝试将表单action改为URI,但问题依旧。

当前Azure面板已配置的环境变量包括:

  • APP_NAME
  • APP_ENV
  • APP_KEY
  • APP_DEBUG
  • APP_TIMEZONE
  • APP_URL
    以及数据库配置和日志相关变量。

注:数据库连接正常,已通过SSH服务器完成数据填充,Azure Data Studio中可看到数据已成功插入。


相关代码

LoginRequest

namespace App\Http\Requests;

use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth; 
use Illuminate\Support\Facades\RateLimiter; 
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;


class LoginRequest extends FormRequest
{
/**
 * Determine if the user is authorized to make this request.
 */
public function authorize(): bool
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
 */
public function rules(): array
{
    return [
        'username' => ['required', 'string'],
        'password' => ['required', 'string']
    ];
}

public function authenticate(): void
{

    if(!Auth::attempt($this->only('username', 'password'), $this->boolean('remember'))){
        \Illuminate\Support\Facades\RateLimiter::hit($this->chave());

        throw \Illuminate\Validation\ValidationException::withMessages([
            'username' => 'Email Incorreto',
            'password' => 'Senha Incorreta',
        ]);


    }
    \Illuminate\Support\Facades\RateLimiter::clear($this->chave());
}

public function limitacao():void
{
    if(!\Illuminate\Support\Facades\RateLimiter::tooManyAttempts($this->chave(), 3)){
        return;
    }
    event(new Lockout($this));

    $seconds = \Illuminate\Support\Facades\RateLimiter::availableIn($this->chave());

    throw \Illuminate\Validation\ValidationException::withMessages([
        'username' => trans('auth.chave', [
            'seconds' => $seconds,
            'minutes' => ceil($seconds / 60)
        ])
    ]);
}

public function chave():string
{
    return \Illuminate\Support\Str::transliterate(\Illuminate\Support\Str::lower($this->string('username')). '|' .$this->ip());
}
}

Controller方法

public function autenticar(LoginRequest $request)
{
    $request->authenticate();

    $request->session()->regenerateToken();

    $msg = 'Bem vindo administrador!';
    session()->flash('message', $msg);

    return redirect()->route('dashboard.index');
}

路由

//rota de login
 Route::get('/login', [LoginController::class , 'index'])->name('login');
 Route::post('/login', [LoginController::class, 'autenticar'])->name('postLogin');

表单

<form class="border-dark-subtle border w-50 p-5 d-flex flex-column align-items-center             justify-content-center gap-5 rounded rounded-3" action="{{route('postLogin')}}" method="post">
            @csrf
            <span class="fs-1 fw-bold text-info">LOGIN</span>
            <div class="d-flex flex-column w-100 gap-3">
                <!-- Inserir Email -->
                <div class="form-floating w-100">
                    <input type="text" class="form-control" id="username" placeholder="Email" name="username">
                    <label>Email</label>
                    @if($errors->has('username') && $errors->has('username'))
                        @if($errors->has('username'))
                            <div class="alert alert-danger">
                                {{$errors->first('username')}}
                            </div>
                        @endif
                    @endif

                </div>

                <!-- Inserir Senha -->
                <div class="form-floating w-100">
                    <input type="password" class="form-control" id="password" placeholder="Senha"
                           name="password">
                    <label>Senha</label>
                    @if($errors->has('password') && $errors->has('password'))
                        @if($errors->has('password'))
                            <div class="alert alert-danger">
                                {{$errors->first('password')}}
                            </div>
                        @endif
                    @endif

                </div>
            </div>
                <label class="alert alert-info" id="numeroLabel" for="">{{$numero_aleatorio}}</label>
            <div class="form-floating w-100 mt-0">
                <input type="text" class="form-control" id="teste" name="">
                <div id="mensagemErro" class="alert alert-danger d-none">Confirme o número acima</div>
            </div>
            <button type="submit" id="submitBtn" class="mt-5 btn btn-info text-light px-5 py-3 fs-5">Entrar</button>

        </form>

解决方案建议

针对XSRF-TOKEN Cookie无效和HTTPS问题,按以下步骤排查修复:

  1. 确认APP_URL环境变量
    确保Azure面板中的APP_URL配置为HTTPS协议的自有域名(例如https://yourdomain.com),而非HTTP或Azure默认域名。Laravel的路由、Cookie生成依赖这个值,错误协议会导致Cookie被浏览器拒绝。

  2. 配置Session Cookie参数
    修改config/session.php中的以下配置:

    'secure' => env('SESSION_SECURE_COOKIE', true), // 强制Cookie仅通过HTTPS传输
    'same_site' => 'lax', // 或根据需求设为'strict',确保跨站请求兼容
    'domain' => env('SESSION_DOMAIN', '.yourdomain.com'), // 主域名前加.,兼容子域名(如果有)
    

    同时在Azure环境变量中添加SESSION_SECURE_COOKIE=true和SESSION_DOMAIN=.yourdomain.com(替换为你的实际域名)。

  3. 强制Laravel使用HTTPS
    在AppServiceProvider的boot方法中添加:

    if (env('APP_ENV') !== 'local') {
        \Illuminate\Support\Facades\URL::forceScheme('https');
    }
    

    确保所有生成的路由链接都是HTTPS协议,避免混合内容导致的安全提示。

  4. 清除缓存
    通过Azure Web App的SSH终端运行以下命令,清除配置和路由缓存:

    php artisan config:clear
    php artisan route:clear
    php artisan cache:clear
    
  5. 检查Azure Web App的HTTPS设置
    确保Azure Web App已启用HTTPS,自定义域名已绑定有效的SSL证书。在Azure面板的"自定义域名"和"TLS/SSL设置"中确认配置正确,强制所有HTTP请求重定向到HTTPS。


内容的提问来源于stack exchange,提问作者laravel_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 14:57:02