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

问题描述 投票:0回答:3

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

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

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

  • 更改了 fortify.php 中的守卫和中间件
  • 更改了可用功能
  • 重新安装了fortify
  • 创建了我自己的 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: '[email protected]',
          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

php laravel authentication fortify
3个回答
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,

0
投票

在你的控制器功能中你可以尝试我知道的方法:

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);
 }

0
投票

如果有人遇到这个问题,经过一番挖掘,我发现了here一些对我有帮助的东西——如果你将

Users
表的ID字段更改为除大整数之外的其他内容,它将导致身份验证失败。

我的迁移文件看起来像这样:

Schema::create('user', function (Blueprint $table) {
    // I wanted to use a UUID.
    $table->uuid()->default(DB::raw("(UUID())"));
    // ...
});

刚刚这样做,启动了新的迁移,一切都按预期进行。

Schema::create('user', function (Blueprint $table) {
    // Just added this.
    $table->id();
    // I wanted to use a UUID.
    $table->uuid()->default(DB::raw("(UUID())"));
    // ...
});
© www.soinside.com 2019 - 2024. All rights reserved.