はてなあたまさんのブログです。

WEB開発勉強中でーす

LaravelでAuth::user()がredirectしたら消えちゃう問題・・T_T

環境: 

Laravel8

php8.1

MAMP


LaravelをAPIだけでしか触った経験しかなくて・・

一人遊びでWebもしてみよーかぁとしたら

ログイン画面から変な感じが・・・www恥ずかしいけどぉ

if (Auth::attempt(['email' => $request->email, 'password' => $request->password], true)) {

とにかく、これでログインしたのに

ログイン後、redirectしたら

Auth::user();

がnullだった・・TT

それで

ネットで調べたみたら

.envのAPP_URL設定を間違えてできなかったようだった・・・

🙄

// 間違ってたやつ
APP_URL=localhost:8888/testProject
SESSION_DOMAIN=localhost:8888/testProject

//これが定番
APP_URL=localhost
SESSION_DOMAIN=localhost

なんでやねん・・?

とにかく、localhostに変えたらいけた。

stackoverflowでは

In short, I needed to remove the http://  protocol from SESSION_DOMAIN  in .env  and set it to match APP_URL

だと書いていた

理由は

When you change the SESSION_DOMAIN env variable, Laravel will issue new cookies but old ones are still in the browsers memory. When the request comes from browser to Laravel app the old cookie has priority and there for you are not able to login.

The solution to this is delete old cookies from the browser (those registered without any domain so to actual host of app).

This error typically bites those who wants to add multi subdomain persistent login. And what is even worse, when you have your application in production already, all your clients will suffer from this issue as well. Nobody will able to login (not only that, but mainly) to your application until they completely clear out their cookies.

I solved this by adding middleware, which does it for me:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Cookie;

class ForgotOldSessionCookies
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        Cookie::queue(new \Symfony\Component\HttpFoundation\Cookie('laravel_session', null, now()->subYear(1)->timestamp, '/'));
        Cookie::queue(new \Symfony\Component\HttpFoundation\Cookie('XSRF-TOKEN', null, now()->subYear(1)->timestamp, '/'));

        return $next($request);
    }
}

Be aware, when you use only this:

Cookie::queue(Cookie::make('laravel_session', null, -6000, '/', 'yourdomain.com'))

or

Cookie::queue(Cookie::forget('laravel_session', '/', 'yourdomain.com'))

Laravel will send Cookie header with domain so browser will create the cookie with domain .yourdomain.com - that's why nothing will be deleted.