简体   繁体   中英

Laravel redirect away method redirects to own domain

I am coding a Laravel API hosted on api.url.com for an application hosted on www.myurl.com on a server different to the Lravel API using Laravel Fortify.

The problem comes when the user verifies their email on the generated link, they are redirected not to the external application but again back to the API, but on their browser.

THe docs state that this configuration in the Authenticate.pgp Middleware would work:

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return url(env('SPA_URL') . '/dashboard');
        }
    }
}

Where SPA_URL is set in the.env to www.myurl.com .

This redirects to api.url.com/www.myurl.com/dashboard Obviously causing a 404 response.

I then tried to call an action on a controller as such

public function redirectDashboard(Request $request){
        return redirect()->away('www.myurl.com/dashboard');
    }

This again redirects to api.url.com/www.myurl.com/dashboard Obviously causing a 404 response.

I have no clue why redirect()->away would still redirect to a url on the same API domain.

Any help would be appreciated, thank you.

The RedirectTo method will redirect to request.

Try to write new middleware

public function handle($request, Closure $next)
{
    //check here if the user is authenticated
    if ( ! $this->auth->user() )
    {
        // here you should redirect to another site
        return redirect(env('SPA_URL') . '/dashboard');
    }

    return $next($request);
}

I finally realised what was happening with the redirect: I was using the redirect() helper function rather than the Redirect::class . The helper function appends the current domain to any url or away method call whereas the Redirect::class allows you to redirect to anywhere you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM