简体   繁体   English

Auth::Check 始终为假,但验证成功 - Laravel 8

[英]Auth::Check is always false but successfully authenticates - Laravel 8

I am currently trying to learn Laravel and I'm hitting a problem with the authentication.我目前正在尝试学习 Laravel 并且遇到了身份验证问题。 I am trying to create an API only laravel project, I'm not using any of the Vue or Blade template files and for the time being have turned off the CSRF validation as I think that was causing me some issues as well when using Insomnia Rest API Client (just want to get the basics initially).我正在尝试仅创建 API laravel 项目,我没有使用任何 Vue 或 Blade 模板文件,并且暂时关闭了 CSRF 验证,因为我认为这在使用 Insomnia Z55276C10D84E11FZ57276C10D84E13 API 客户端(只是想初步了解基础知识)。

I have two simple API routes, one that does the login and one that checks I am logged in that should return the user details.我有两条简单的 API 路由,一条用于登录,一条用于检查我是否已登录,应该返回用户详细信息。

I am using my own database and Users model to do the authentication.我正在使用自己的数据库和用户 model 进行身份验证。

My Users model is as follows:我的用户 model 如下:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class Users extends Authenticatable
{
    use HasFactory;

    protected $table = "users";
    protected $primaryKey = "UserID";

    protected $casts = [
        "IsActive" => "boolean"
    ];
}

In my api.php I have the following在我的 api.php 我有以下

Route::prefix("/login") ->group(__DIR__ . '/login.php');

Then in login.php I have the following然后在 login.php 我有以下

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LoginController;
Route::post('/', [LoginController::class, 'login']);
Route::get('/', [LoginController::class, 'getLoggedInUser']);

My LoginController class is set up as follows:我的 LoginController class 设置如下:

namespace App\Http\Controllers;

use App\Models\Users as User;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api')->except('login', 'getLoggedInUser');
        //$this->middleware('admin')->except('login', 'forgot', 'getLoggedInUser');
    }

Then in my LoginController I have the following for the post login request to actually perform the authentication:然后在我的 LoginController 中,我有以下登录请求以实际执行身份验证:

public function login(Request $request)
    {
        $user = User::where("Username", "my_username")->where("Password", "my_password")->first();

        if ($user !== null)
        {
            if ($user->AccountActive)
            {
                \Auth::login($user);
                
                return \response(["status" => "authenticated", "auth'd user" => \Auth::user(), "logged_in" => \Auth::check()], 200);
            }
            else
            {
                return \response(["status" => "Your account has been disabled"], 401);
            }
        }
        else
        {
            return \response(["status" => "failed"], 401);
        }
    }

As you can see above, I'm currently hard coding the user credentials currently using the string values that are in the database instead of checking anything in the request currently.正如您在上面看到的,我目前正在使用数据库中的字符串值对当前用户凭据进行硬编码,而不是当前检查请求中的任何内容。

The above login returns the following response:上述登录返回以下响应:

{
  "status": "authenticated",
  "auth'd user": {
    "UserID": 1,
    "LastLoggedIn": "2020-01-16 18:29:37",
    "Username": "my_username",
    "Password": "my_password",
    "AuthToken": "0",
    "Email": "",
    "AccountActive": "1"
  },
  "logged_in": true
}

In my check if I am logged in route, I have the following:在我检查我是否登录路由时,我有以下内容:

public function getLoggedInUser(Request $request)
    {
        return [
            "logged_in" => \Auth::check(),
            "status" => "success",
            "user" => \Auth::user()
        ];
    }

When I do the above I then get the following response:当我执行上述操作时,我会得到以下响应:

{
  "logged_in": false,
  "status": "success",
  "user": null
}

So as you can see its acting as if I'm no longer authenticated.因此,您可以看到它的行为就好像我不再经过身份验证一样。

HTTP requests are stateless, to get around this things like sessions are used to store state between requests. HTTP 请求是无状态的,为了解决这个问题,例如会话用于在请求之间存储 state。 Even though you have authenticated yourself via login, no state has been retained anywhere to associate requests with you.即使您已通过登录验证了自己,也没有任何 state 被保留在任何地方以将请求与您关联。

APIs don't use sessions therefore you need some other mechanism to send along with each subsequent request which can be checked by the server to determine who has made the request and if they are authorised to perform the requested action. API 不使用会话,因此您需要一些其他机制与每个后续请求一起发送,服务器可以检查这些请求以确定谁发出了请求以及他们是否有权执行请求的操作。

For Laravel, this is where the Sanctum and Passport packages come in. They provide auth workflows for APIs.对于 Laravel,这就是SanctumPassport包的用武之地。它们为 API 提供身份验证工作流。

Whilst everyones learning journey is different and people learn in different ways, I feel like you might be making your learning Laravel more difficult than it needs to be by avoiding using the packages it provides.虽然每个人的学习历程都不同,而且人们的学习方式也不同,但我觉得您可能会因为避免使用它提供的软件包而使您的学习 Laravel 变得更加困难。 After all, one of the reasons for using Laravel, or any sort of framework for that matter, is to leverage the features it provides to simplify your life.毕竟,使用 Laravel 或任何类型的框架的原因之一是利用它提供的功能来简化您的生活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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