简体   繁体   English

Laravel/Lumen + JWT + User 自定义模型中的 Auth 尝试方法如何工作

[英]How does Auth attempt method work in Laravel/Lumen + JWT + User custom model

I have spent a day trying to understand how to inject JWT auth in my API, but unfortunately I have not got any success.我花了一天时间试图了解如何在我的 API 中注入 JWT 身份验证,但不幸的是我没有取得任何成功。

I am using Lumen framework.我正在使用流明框架。 There is, I think great, library for JWT Auth JWT For Lumen And Laravel .我认为 JWT Auth JWT For Lumen 和 Laravel 的很棒 I have successfully installed it by composer, it looks like it works ok, but I have not default User model in my project, I can easily migrate to the default, but I want to understand how does all this stuff work.我已经通过 composer 成功安装了它,看起来它工作正常,但是我的项目中没有默认的 User 模型,我可以轻松迁移到默认模型,但我想了解所有这些东西是如何工作的。

I will not post example code here, to make question shorter, here it is JWT Example .我不会在这里发布示例代码,为了缩短问题,这里是JWT Example

I am relatively new to Laravel and Lumen , so maybe my question is already answered, but I have spent several hours trying to find documentation and understand Auth core in the framework.我对LaravelLumen比较陌生,所以也许我的问题已经得到解答,但我花了几个小时试图找到文档并了解框架中的Auth核心。

I have custom User Model我有自定义用户模型

<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
    const CREATED_AT = 'createTime';
    const UPDATED_AT = 'updateTime';
    public $timestamps = true;
    protected $table = 'user';
    protected $guarded = ['password','login','id','activationEmail'];
    protected $hidden = [ 'password' ];
    protected function getDateFormat()
    {
        return 'U';
    }
}

And of course custom controller to route request to it.当然还有自定义控制器将请求路由到它。

But the problem is that as I recently discovered that JWT library uses Auth to implement jwt authentication.但问题是,最近我发现JWT 库使用Auth来实现 jwt 身份验证。

And Auth do some magic stuff with default User model which in turn impements UserInterface , should my model also implement this interface ?并且Auth使用默认的 User 模型做一些神奇的事情,这反过来又会影响UserInterface ,我的模型是否也应该实现这个接口?

I have tried explicitly specify my model in config, but nevertheless it tries to use old model and throws exception that App\\User not found.我已经尝试在配置中明确指定我的模型,但它仍然尝试使用旧模型并抛出App\\User未找到的异常。

Please help to find answers for these questions :请帮助找到这些问题的答案:

  1. How does framework by default knows what is the name of my users table and what fields does it have ?默认情况下,框架如何知道我的用户表的名称以及它有哪些字段? Or it assumes that it has users name and columns of the table are common like email,login, password and so on.或者它假设它具有用户名和表的列是常见的,如电子邮件、登录名、密码等。

  2. What happens when attempt method is invoked ?调用尝试方法时会发生什么? Framework tries to find user by the email for example, if was found, password is checked ?框架尝试通过电子邮件查找用户,例如,如果找到,则检查密码?

  3. How to specify my custom model, I have tried to change config and got exceptions described in this question Missing argument 1 for Illuminate\\Auth\\AuthManager::createDriver() lumen and JWT如何指定我的自定义模型,我尝试更改配置并得到了这个问题Missing argument 1 for Illuminate\\Auth\\AuthManager::createDriver() lumen and JWT 中描述的异常

I would be grateful if someone help to solve and understand this problem.如果有人帮助解决和理解这个问题,我将不胜感激。

Thanks everyone for any help.感谢大家的帮助。

Well good question, by default the users table in laravel is going to be users.好问题,默认情况下,laravel 中的 users 表将是 users。

You can set the table name within the model by using the $table property.您可以使用 $table 属性在模型中设置表名。

  1. Think of a Model as a representation of a database.将模型视为数据库的表示。 If you have a table called books, you would typically have a model called Books.如果您有一个名为 books 的表,您通常会有一个名为 Books 的模型。 Also within Laravel, to generate a model, from the command line run php artisan make:model ModelName.同样在 Laravel 中,要生成模型,请从命令行运行 php artisan make:model ModelName。 This will do most of the work for you.这将为您完成大部分工作。

  2. When Auth::attempt() is invoked, you pass through a array of credentials and it will match those up against your database.当 Auth::attempt() 被调用时,你会传递一个凭据数组,它会将这些凭据与你的数据库进行匹配。 So you could do Auth::attempt(['email' => $email, 'password' => $password]) or Auth::attempt(['username' => $username, 'password' => $password, 'active' => 1], $remember) .所以你可以做Auth::attempt(['email' => $email, 'password' => $password])Auth::attempt(['username' => $username, 'password' => $password, 'active' => 1], $remember) Yes, the password is checked, you can also manually check a password with Hash::check().是的,密码已检查,您也可以使用 Hash::check() 手动检查密码。

  3. When creating a custom model, use the php artisan generate command to make your model for you.创建自定义模型时,请使用 php artisan generate 命令为您制作模型。 Then change the namespace to your directory structure to composer can autoload that class in for you (only if you move the model to say a models directory).然后将命名空间更改为您的目录结构,以便 composer 可以为您自动加载该类(仅当您将模型移动到模型目录时)。 From there you will not have to do anything to interact with your database, again a model just represents a table.从那里你不需要做任何事情来与你的数据库进行交互,同样一个模型只是代表一个表。 Unless you create a model called AllBooks to represent a Books table, you would need to define the $table property to be $table = 'Books';除非您创建一个名为 AllBooks 的模型来表示 Books 表,否则您需要将$table属性定义为$table = 'Books'; . .

I would really recommend learning object orientated in-depth before you jump into a framework like Laravel.在你跳入 Laravel 这样的框架之前,我真的建议你深入学习面向对象。 While it is great you want to do this, it can mislead you.虽然您想这样做很好,但它可能会误导您。

Also a quick tip, if you are going to continue with laravel/lumen.如果您打算继续使用 laravel/lumen,也是一个快速提示。 When creating a table, remember to add an updated_at and created_at datetime field, if you do not do this set the timestamp property to false within the model like so: public $timestamps = false;创建表时,请记住添加一个 updated_at 和 created_at 日期时间字段,如果您不这样做,请将模型中的时间戳属性设置为 false,如下所示: public $timestamps = false; . .

Best of luck!祝你好运!

  • Login - auth登录 - 认证
    • From route-> call your controller using post method从路由-> 使用 post 方法调用您的控制器
    • In the auth controller, validate the request like,在身份验证控制器中,验证请求,例如,
      • $this->validate($request, [ 'email' => 'required|email|max:255', 'password' => 'required', ]); $this->validate($request, [ 'email' => 'required|email|max:255', 'password' => 'required', ]);
      • If this is successfully validated,如果验证成功,
        • JWTAuth::attempt($credentials); JWTAuth::attempt($credentials); // credentials should be in array format like array('email' => 'dbfieldname', 'password') // 凭据应采用数组格式,如 array('email' => 'dbfieldname', 'password')
      • if not valid, throw error like,如果无效,则抛出错误,例如,
        • response()->json(['error' => 'invalid_credentials', 'message' => 'Invalid Credentials'], 401) response()->json(['error' => 'invalid_credentials', 'message' => 'Invalid Credentials'], 401)
      • If success, generate token like,如果成功,生成令牌,如,
        • response()->json(compact('token')); response()->json(compact('token'));

Implement JWT in laravel is very tiring and confusing, you'll always missing packages and arguments.在 laravel 中实现 JWT 非常累人且令人困惑,你总是会丢失包和参数。

try this laravel/lumen package : dingo-api试试这个 laravel/lumen 包: dingo-api

and here is a simple exemple project which could demostrate the full life cycle of jwt auth.这是一个简单的示例项目,可以演示 jwt auth 的整个生命周期。 This one is very easy to debug.这个很容易调试。 dingo-api-demo dingo-api-演示

in the dingo-api-demo project, you may find most of answers to your questions in these following locations在 dingo-api-demo 项目中,您可以在以下位置找到大部分问题的答案

  1. /config/jwt.php /config/jwt.php
  2. /config/api.php /config/api.php
  3. /config/auth.php /config/auth.php

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

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