简体   繁体   English

Auth::user() 在 Laravel 5.8 中返回 null

[英]Auth::user() return null in Laravel 5.8

I'm having a problem with authentication in my Laravel 5.8.10 project.我在 Laravel 5.8.10 项目中遇到身份验证问题。 I am not using the default form that Laravel creates for authentication.我没有使用 Laravel 为身份验证创建的默认表单。 When I access the URL/dashboard in a browser, typically the user would get redirected redirect upon login.当我在浏览器中访问 URL/仪表板时,通常用户会在登录时被重定向。 The application allows it anyway.无论如何,应用程序允许它。 Also when I give use Auth::user() it returns null.此外,当我使用Auth::user()它返回 null。

When I type an invalid username and password, it's not passed from the login screen.当我输入无效的用户名和密码时,它不会从登录屏幕传递。 When I type invalid credentials it redirects to the dashboard.当我输入无效凭据时,它会重定向到仪表板。 The problem of accessing the URL through the dashboard view also continues.通过仪表板视图访问 URL 的问题也在继续。 It's as if you do not need authentication to access the route.就好像您不需要身份验证即可访问路由。

Note: I have in my .env file a variable PASSWORD_HASH to enable or disable password encryption.注意:我的 .env 文件中有一个变量PASSWORD_HASH来启用或禁用密码加密。

User model用户模型

namespace App\Entities;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;

    protected $table = "users";
    public $timestamps = true;

    protected $fillable = [
        'cpf', 'name', 'phone', 'birth', 'gender', 'notes', 'email', 'password', 'status', 'permission'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function groups()
    {
        return $this->belongsToMany(Group::Class, 'user_groups');
    }

    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = env('PASSWORD_HASH') ? bcrypt($value) : $value;
    }
}

config/auth.php配置/auth.php

return [
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Entities\User::class,
        ],
    ],
    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],
];

DashboardController仪表盘控制器

public function auth(Request $request)
{
    $data = [
        'email' => $request->get('username'),
        'password' => $request->get('password')
    ];
    try {
        if (env('PASSWORD_HASH')) {
            Auth::attempt($data, false);
        } else {
            $user = $this->repository->findWhere(['email' => $request->get('username')])->first();

            if (!$user)
                throw new Exception("O e-mail informado é inválido. PEEEEN!");
            if ($user->password != $request->get('password'))
                throw new Exception("A senha informada é inválida. PEEEEN!");
            Auth::login($user);
        }
        return redirect()->route('user.dashboard');
    } catch (Exception $e) {
        return $e->getMessage();
    }
}

Routes路线

Route::get('/login', ['uses' => 'Controller@fazerlogin']);
Route::post('/login', ['as' => 'user.login', 'uses' => 'DashboardController@auth']);
Route::get('/dashboard', ['as' => 'user.dashboard', 'uses' => 'DashboardController@index']);

View login查看登录

<section id="conteudo-view" class="login">
    <h1>Investindo</h1>
    <h3>O nosso gerenciador de investimento</h3>
    {!! Form::open(['route' => 'user.login', 'method' => 'post']) !!}
    <p>Acesse o sistema</p>
    <label>
        {!! Form::text('username', null, ['class' => 'input', 'placeholder' => "Usuário"]) !!}
    </label>
    <label>
        {!! Form::password('password', ['placeholder' => 'Senha']) !!}
    </label>
    {!! Form::submit('Entrar') !!}
    {!! Form::close() !!}
</section>

.env .env

PASSWORD_HASH=false

The idea is that when it's false when registering a user it stops encrypting the password, and when true, do the encryption.这个想法是,当注册用户时为假,它停止加密密码,当为真时,进行加密。 This is working.这是有效的。

Database User数据库用户

https://pasteboard.co/IcMC2ds.png https://pasteboard.co/IcMC2ds.png

  1. to stop redirecting to dashboard without auth use auth middleware route停止重定向到没有身份验证的仪表板使用身份验证中间件路由

    Route::middleware(['auth'])->group(function () { Route::get('/dashboard', ['as' => 'user.dashboard', 'uses' => 'DashboardController@index']); });
  2. env return string, not boolean values so use env('PASSWORD_HASH') == 'true' to check password hash is enable or not env 返回字符串,而不是布尔值,因此使用env('PASSWORD_HASH') == 'true'来检查密码哈希是否启用

  3. use loginUsingId() to login in manually.使用loginUsingId()手动登录。

     if(env('PASSWORD_HASH') == 'true') { Auth::attempt($data, false); } else { $user = User::where('email', $request->username)->where('password', $request->password)->first(); if(!$user){ throw new Exception("O e-mail informado é inválido. PEEEEN!"); } else { Auth::loginUsingId($user->id); //redirect } }

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

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