Laravel Fortify 登录后重定向,但不登录用户

Posted

技术标签:

【中文标题】Laravel Fortify 登录后重定向,但不登录用户【英文标题】:Laravel Fortify redirects after login, but doesn't login user 【发布时间】:2022-01-10 02:37:47 【问题描述】:

我正在尝试使用 Fortify 制作一个简单的身份验证系统。我的前端是 React JS。一周前我尝试了强化基本功能,一切都运行良好。但是现在我尝试它没有任何效果。具体来说:

在向 /auth/login 发送 POST 请求后,fortify 将我重定向到 /,就好像我已经登录一样,但是当我执行 Auth::check() 时,它给出了错误。我也通过邮递员尝试过,同样的事情发生 注册一个人有效。它在数据库中创建一个新条目并重定向到 /。但它也没有登录使用

我已经尝试了很多方法来解决这个问题(恢复了所有更改,因为它们不起作用):

更改了 fortify.php 中的保护和中间件 更改了可用功能 重新安装强化 创建了我自己的 Fortify::authenticateUsing() 尝试删除所有其他路径 没有任何效果

补充说明:

Route::get('/path?', ... 用于路由到 React 应用的所有路由

fortify.php

<?php

use App\Providers\RouteServiceProvider;
use Laravel\Fortify\Features;

return [

   /*
   |--------------------------------------------------------------------------
   | Fortify Guard
   |--------------------------------------------------------------------------
   |
   | Here you may specify which authentication guard Fortify will use while
   | authenticating users. This value should correspond with one of your
   | guards that is already present in your "auth" configuration file.
   |
   */

   'guard' => 'web',

   /*
   |--------------------------------------------------------------------------
   | Fortify Password Broker
   |--------------------------------------------------------------------------
   |
   | Here you may specify which password broker Fortify can use when a user
   | is resetting their password. This configured value should match one
   | of your password brokers setup in your "auth" configuration file.
   |
   */

   'passwords' => 'users',

   /*
   |--------------------------------------------------------------------------
   | Username / Email
   |--------------------------------------------------------------------------
   |
   | This value defines which model attribute should be considered as your
   | application's "username" field. Typically, this might be the email
   | address of the users but you are free to change this value here.
   |
   | Out of the box, Fortify expects forgot password and reset password
   | requests to have a field named 'email'. If the application uses
   | another name for the field you may define it below as needed.
   |
   */

   'username' => 'email',

   'email' => 'email',

   /*
   |--------------------------------------------------------------------------
   | Home Path
   |--------------------------------------------------------------------------
   |
   | Here you may configure the path where users will get redirected during
   | authentication or password reset when the operations are successful
   | and the user is authenticated. You are free to change this value.
   |
   */

   'home' => RouteServiceProvider::HOME,

   /*
   |--------------------------------------------------------------------------
   | Fortify Routes Prefix / Subdomain
   |--------------------------------------------------------------------------
   |
   | Here you may specify which prefix Fortify will assign to all the routes
   | that it registers with the application. If necessary, you may change
   | subdomain under which all of the Fortify routes will be available.
   |
   */

   'prefix' => 'auth',

   'domain' => null,

   /*
   |--------------------------------------------------------------------------
   | Fortify Routes Middleware
   |--------------------------------------------------------------------------
   |
   | Here you may specify which middleware Fortify will assign to the routes
   | that it registers with the application. If necessary, you may change
   | these middleware but typically this provided default is preferred.
   |
   */

   'middleware' => ['web'],

   /*
   |--------------------------------------------------------------------------
   | Rate Limiting
   |--------------------------------------------------------------------------
   |
   | By default, Fortify will throttle logins to five requests per minute for
   | every email and IP address combination. However, if you would like to
   | specify a custom rate limiter to call then you may specify it here.
   |
   */

   'limiters' => [
       'login' => 'login',
       'two-factor' => 'two-factor',
   ],

   /*
   |--------------------------------------------------------------------------
   | Register View Routes
   |--------------------------------------------------------------------------
   |
   | Here you may specify if the routes returning views should be disabled as
   | you may not need them when building your own application. This may be
   | especially true if you're writing a custom single-page application.
   |
   */

   'views' => false,

   /*
   |--------------------------------------------------------------------------
   | Features
   |--------------------------------------------------------------------------
   |
   | Some of the Fortify features are optional. You may disable the features
   | by removing them from this array. You're free to only remove some of
   | these features or you can even remove all of these if you need to.
   |
   */

   'features' => [
       Features::registration(),
       Features::resetPasswords(),
       // Features::emailVerification(),
       Features::updateProfileInformation(),
       Features::updatePasswords(),
       Features::twoFactorAuthentication([
           'confirmPassword' => true,
       ]),
   ],

];

FortifyServiceProvider

<?php

namespace App\Providers;

use App\Models\User;
use Illuminate\Http\Request;
use Laravel\Fortify\Fortify;
use Illuminate\Support\Facades\Hash;
use App\Actions\Fortify\CreateNewUser;
use Illuminate\Support\ServiceProvider;
use Illuminate\Cache\RateLimiting\Limit;
use App\Actions\Fortify\ResetUserPassword;
use App\Actions\Fortify\UpdateUserPassword;
use Illuminate\Support\Facades\RateLimiter;
use App\Actions\Fortify\UpdateUserProfileInformation;

class FortifyServiceProvider extends ServiceProvider

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    
        //
    

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    
        Fortify::createUsersUsing(CreateNewUser::class);
        Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
        Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
        Fortify::resetUserPasswordsUsing(ResetUserPassword::class);

        RateLimiter::for('login', function (Request $request) 
            return Limit::perMinute(5)->by($request->email.$request->ip());
        );

        RateLimiter::for('two-factor', function (Request $request) 
            return Limit::perMinute(5)->by($request->session()->get('login.id'));
        );
    

Web.php

<?php

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LoginController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();

Route::get('/path?', function () 
    return view('app');
)->where('path', '.*')->middleware('auth');

react 应用的测试代码

    const Login = () =>
    axios(
        method: 'post',
        url: '/auth/login',
        data: 
          email: 'leon@gmail.com',
          password: 'password'
        
      ).then((res) => console.log(res))
      .catch((err) => console.log(err));

用于检查用户是否登录的APIController

    public function checkIfLoggedIn()
        if (Auth::check()) 
            return response()->json(['message' => 'Logged in']);
        
        return response()->json(['message' => 'Not logged in']);
    

我已经尝试修复此问题 3 小时了,感谢您提供任何帮助。谢谢 如果您需要更多代码,这里是 github 存储库:https://github.com/LeonLav77/M-Store.git

【问题讨论】:

【参考方案1】:

在您的控制器功能中,您可以尝试我知道的方式:

public function checkIfLoggedIn(Request $request) 
   // with this you can get the info of the user logged in
   // $loggedUser = auth()->user();
   // check from $request->user() if auth()->user() not working
   $message = ( $request->user() ) ? ['message' => 'Logged In'] : ['message' => 
              'Not Logged In'];
   return response()->json($message);
 

【讨论】:

谢谢回复,但是输出还是一样的:/【参考方案2】:

我猜在中间件过程中的某个地方我删除了启动会话的能力,修复是添加

\Illuminate\Session\Middleware\StartSession::class

到内核 php

protected $middleware = [
    // \App\Http\Middleware\TrustHosts::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \App\Http\Middleware\TrustProxies::class,
    \Fruitcake\Cors\HandleCors::class,

【讨论】:

以上是关于Laravel Fortify 登录后重定向,但不登录用户的主要内容,如果未能解决你的问题,请参考以下文章

在 Laravel 中登录多个角色后重定向

登录laravel 5.7后重定向到上一页

laravel 5.2 登录后重定向到预期的网址

如何将客人重定向到登录页面,在laravel 5.2登录后重定向回来[关闭]

如何在laravel中登录后重定向特定页面

Laravel Fortify 自定义身份验证重定向