簡體   English   中英

Laravel Fortify 登錄后重定向,但不登錄用戶

[英]Laravel Fortify redirects after login, but doesn't login user

我正在嘗試使用 Fortify 制作一個簡單的身份驗證系統。 我的前端是 React JS。 一周前我嘗試了強化基本功能,一切運行良好。 但是現在我嘗試它沒有任何效果。 再具體一點:

  • 在向 /auth/login 發送 POST 請求后,fortify 將我重定向到 /,就好像我已經登錄一樣,但是當我執行 Auth::check() 時,它給出了錯誤。 我也試過通過Postman,同樣的事情發生
  • 注冊一個人的作品。 它在數據庫中創建一個新條目並重定向到 /。 但它也沒有登錄使用

我已經嘗試了很多方法來解決這個問題(恢復所有更改,因為它們不起作用):

  • 更改了 fortify.php 中的保護和中間件
  • 更改了可用功能
  • 重新安裝強化
  • 創建了我自己的 Fortify::authenticateUsing()
  • 嘗試刪除所有其他路徑 沒有任何效果

額外說明:

  • Route::get('/{path?}', ... 用於路由到反應應用程序的所有路由

強化.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');

從反應應用程序進行測試的代碼

    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.ZBA9F11ECC3497D9993B933FDC2BD61E5

在您的 controller function 中,您可以嘗試我知道的方式:

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

我想在中間件過程中的某個地方我刪除了啟動會話的能力修復是添加

\Illuminate\Session\Middleware\StartSession::class

至 kernel php

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM