Search code examples
phplaravelauthenticationiframecsrf-token

Embedded Laravel App In Iframe, Give 302 Error On Login


I'm trying to use the Laravel app in some other domain within iframe.

I had written a FrameMiddleware in which I have allowed that domain in the header

 public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        $response->header('Content-Security-Policy', 'frame-ancestors http://localhost');
        return $response;
    }

and by using the above middleware cors origin error removed.

As my Laravel app needs authentication from the iframe. and it's using form submission, not API. Then it starts to give a
419 error. I resolved by adding a login route in VerifyCsrfToken Middleware $except array for excluding csrf error.

then I check network and the post request for login give 302 error

laravel within iframe give 302 error for post request

I tested the authentication method and authenticated user object is returning with Dashboard page redirect and then 302 error code shown.

Moreover, I had set same_site => null in config/session.php but still not working.


Solution

  • As @apokryfos said, I need to set the cookie to be secure and set SameSite=None.

    Goto : config/session.php

    set: 'same_site' => 'none' and 'secure' => env('SESSION_SECURE_COOKIE', true) OR by setting SESSION_SECURE_COOKIE = true in .env file.

    and don't forget to create FrameMiddleware as you can follow-my-question-thread and white_labeled the domain i.e http://localhost in which you are embedding iframe.

    Note: you can verify cookies are secured or not along with SameSite=Null by using browser dev-tools as shown in the below image:

    cookies secured and SameSite=Null Verification