【问题标题】:Throw not found error if user not exist in database Laravel如果数据库 Laravel 中不存在用户,则抛出未找到错误
【发布时间】:2021-07-07 03:15:35
【问题描述】:

我正在使用Auth::attempt($credentials) 来验证来自用户的登录数据。

$credentials = [
    'user_name' => $request->user_name,
    'password' => $request->password,
];

if (Auth::attempt($credentials)) {
    return redirect()->route('admin.dashboard');
} else {
    return redirect()->back()->with('status', 'Invalid credentials!');
}

如果用户输入了错误的密码或用户名,我会抛出一个无效的凭据错误。但是我想如果数据库中不存在用户,我可以抛出用户不存在的错误。

我的Auth::attempt($credentials) 返回真或假,所以我不知道该怎么做。你能帮忙吗?

【问题讨论】:

  • 抛出 404 实际上可能被认为是一个安全漏洞,因为您将有关有效帐户用户名的信息暴露给潜在的攻击者。为什么要这样做?
  • 这个问题可以改写成:“我如何检查用户是否已经存在”所以我建议调查一下:stackoverflow.com/questions/42416753/… 但正如@fubar 提到的,一个模糊的“用户名/密码不正确”应该足够;除非您正在注册,否则无需说明“用户名已被占用”。
  • 非常感谢您的所有建议,我终于解决了问题。

标签: laravel authentication


【解决方案1】:
$user = User::where('user_name',$request->user_name)->first();

if($user) {
  $credentials = [
    'user_name' => $request->user_name,
    'password' => $request->password,
  ];

  if (Auth::attempt($credentials)) {
    return redirect()->route('admin.dashboard');
  } else {
    return redirect()->back()->with('status', 'Invalid credentials!');
  } 
} else {
  return redirect()->back()->with('status', 'Not found!');
}

【讨论】:

    【解决方案2】:

    正如@fubar 所说,先生,这将是一个安全问题,但简单的逻辑是

    1. 如果存在电子邮件,请在 users 表中查找。
    2. 如果存在,则按照您已经实施的方式进行身份验证尝试。
    3. 如果不存在,则抛出 404。

    【讨论】:

      猜你喜欢
      • 2020-01-03
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 2021-06-13
      • 2016-10-17
      • 1970-01-01
      • 2014-10-25
      相关资源
      最近更新 更多