使 Laravel 模型具备认证功能

huangapple go评论54阅读模式
英文:

Make Laravel Model Authenticatable

问题

我想要一个不同的模型,也能够登录。

这个模型的名称是 Client

所以要将以下内容添加到 auth.php 配置文件中:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'client' => [
        'driver' => 'session',
        'provider' => 'clients',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'clients' => [
        'driver' => 'eloquent',
        'model' => App\Models\Client::class,
    ],
],

然后期望以下代码可以工作:

Auth::guard('client')->loginUsingId($client->id, true);

但是这段代码没有显示任何已验证的客户端:

return Auth::guard('client')->user();

我漏掉了什么?

路由应该像这样设置:

Route::group(['middleware' => ['auth:client']], function () {     
    Route::get('my-orders', [OrderController::class, 'index']); // 转到登录路由
});

这是登录代码:

Auth::guard('client')->loginUsingId($client->id, true); 
ray(['Auth' => Auth::guard('client')->user()]); // 显示正确的 Auth
return redirect()->to("/{$locale}/my-orders"); // 重新导向到登录路由

希望这些信息对你有所帮助。

英文:

I want a different Model the be able to login too.

The name of the Model is Client.

So this is added this to auth.php config:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'client' => [
        'driver' => 'session',
        'provider' => 'clients',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],

    'clients' => [
        'driver' => 'eloquent',
        'model' => App\Models\Client::class,
    ],
],

And expected that this should work:
Auth::guard('client')->loginUsingId($client->id, true);

But this doesn't show any Authenticated Client:
return Auth::guard('client')->user();

What am I missing?

Routes are like this:

Route::group(['middleware' => ['auth:client']], function () {     
   Route::get('my-orders', [OrderController::class, 'index']); //goes to login route });

This is the login code:

Auth::guard('client')->loginUsingId($client->id, true); 
ray(['Auth' => Auth::guard('client')->user()]); // Shows correct Auth
return redirect()->to("/{$locale}/my-orders"); // Re-redirects to Login route

答案1

得分: 0

If you're using auth in another model, you have to use Illuminate\Contracts\Auth\Authenticatable interface and Illuminate\Auth\Authenticatable trait.

Example:

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;

class Client extends Model implements AuthenticatableContract
{
    use Authenticatable;
}

Then, run:

php artisan config:cache

After that, these will work:

Auth::guard('client')->loginUsingId($client->id, true)
Auth::guard('client')->user()

Make sure you've required columns email or username and password and remember_token.

Edit 01

In redirectIfAuthenticated (located in app/Http/Middleware/RedirectIfAuthenticated.php), add this:

public function handle($request, Closure $next, ...$guards)
{
    $guards = empty($guards) ? [null] : $guards;

    foreach ($guards as $guard) {
        if (Auth::guard($guard)->check()) {
            switch ($guard) {
                case 'client':
                    return redirect(route('client.dashboard'));
                default:
                    return redirect(RouteServiceProvider::HOME);
            }
        }
    }

    return $next($request);
}

Updating middleware to be aware of the new guard.

英文:

If you're using auth in another model you have to use Illuminate\Contracts\Auth\Authenticatable interface and Illuminate\Auth\Authenticatable trait

Example

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;

class Client extends Model implements AuthenticatableContract
{
    use Authenticatable;

}

then

php artisan config:cache

after that, these will work

Auth::guard('client')->loginUsingId($client->id, true)
Auth::guard('client')->user()

> Make sure you've required columns email or username and password and remember_token


Edit 01

In redirectIfAuthenticated(located in app/Http/Middleware/RedirectIfAuthenticated.php)

add this

public function handle($request, Closure $next, ...$guards)
{
    $guards = empty($guards) ? [null] : $guards;

    foreach ($guards as $guard) {
        if (Auth::guard($guard)->check()) {
            switch ($guard) {
                case 'client':
                    return redirect(route('client.dashboard'));
                default:
                    return redirect(RouteServiceProvider::HOME);
            }
        }
    }

    return $next($request);
}

>Updating middleware to be aware of the new guard.

答案2

得分: -1

你需要在Laravel中使用默认的身份验证,同时使用多个模型和多个守卫来执行一系列步骤。

以下是一些详细信息:

1 - 首先,您必须在文件“config/auth.php”中添加多个守卫。您似乎已经完成了这一步,所以我不会再解释它。

2 - 您必须在模型中指定守卫,使用以下代码:

protected $guard = "guard_name";

同时,要使用身份验证特性并实现身份验证接口。

3 - 您需要对“LoginController”(位于“app/Http/Controllers/Auth”目录下)进行一些更改。

4 - 同样,您还需要对“RegisterController”(位于“app/Http/Controllers/Auth”目录下)进行一些修改。

5 - 您必须指定注册后用户将前往的位置,基于守卫,是否是控制面板或主页。默认情况下是主页。

6 - 您需要修改中间件,也可以在“RedirectIfAuthenticated.php”中进行修改。

7 - 您可能还需要修改处理程序类,可以在“app/Exceptions/Handler.php”中进行修改。

8 - 当然,您还需要修改视图。

9 - 您可能还需要修改路由。

我认为这就是您需要的全部内容。

以下是一些参考链接,可帮助您了解需要在代码中进行的修改,并提供示例:

https://techvblogs.com/blog/multiple-authentication-guards-laravel-9

英文:

You need to use the default auth in Laravel with more than one model and more than one guard
to make a set of steps

Here are some details ..

1 - You must first add more than one guard
from file "config/auth.php"

Indeed, you did this step, so I will not explain it

2 - You must specify guard in model

using the protected $guard = "guard_name"

And use the auth trait

and implement auth interface

3 - You have to make some changes to the

"LoginController" in this place "app/Http/Controllers/Auth"

4 - You should also do some modifications to the

"RegisterController" in this place "app/Http/Controllers/Auth"

5 - You must specify the place where the person who registers will go after registration, based on the gurd, if it is the control panel or the home page

By default it is the home page

6 - You have to modify the middleware
also
From this place

"RedirectIfAuthenticated.php"

7 - You may also need to modify the handler class
From this place

"app/Exceptions/Handler.php"

8 - And of course you have to modify the views

9 - You may also need to modify the route

I think that's all you need

Here are some references to know what needs to be modified in the code with an example

https://techvblogs.com/blog/multiple-authentication-guards-laravel-9

答案3

得分: -1

以下是已翻译的内容:

可能有一些原因导致未使用“client guard”进行身份验证:

  • 请求根本未经过身份验证。这可能是因为用户尚未登录,或者因为请求使用了未经授权的方法,例如GET
  • 请求是使用不同的守卫进行身份验证的。这可能是因为用户使用了不同的守卫登录,例如web

因此,请验证当前请求是否使用“client guard”进行身份验证,方法如下:

auth()->guard('client')->check()

用户是否已经通过身份验证?

返回:

  • 真(1)或假(0)

如果要强制使用它:

$user = User::find(1);

if (auth()->guard('client')->login($user)) {
    // 用户现在已经使用“client”守卫登录。
} else {
    // 登录失败。
}

这将为您提供为何失败的很好理解。希望对您有所帮助!

英文:

There might be a few reasons why is NOT authenticating using the client guard:

  • The request is not authenticated at all. This could be because the
    user has not logged in, or because the request is using an
    unauthorized method, such as GET.
  • The request is authenticated using a different guard. This could be
    because the user is logged in using a different guard, such as web.

So, verify that the current request is authenticated using the client guard, with this method:

auth()->guard('client')->check()

Is the user Authenticated? Returns:

true (1) OR false (0)

To force it use:

$user = User::find(1);

if (auth()->guard('client')->login($user)) {
// The user is now logged in using the `client` guard.
} else {
// The login failed.
}

This would give you a good idea of why is failing. I hope it helps!

huangapple
  • 本文由 发表于 2023年6月8日 22:44:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定