简体   繁体   English

如何更改 laravel 9 中“记住我”cookie 的持续时间?

[英]How to change duration of "remember me" cookie in laravel 9?

I'm using laravel 9 and implementing login authentication manually without the laravel starter kit , I've read a lot of questions like this but most of the answers only apply to those using the starter kit, I've also read some of the other answers without the starter kit but most of them don't work.我正在使用 laravel 9 并在没有laravel 入门套件的情况下手动实施登录身份验证,我已经阅读了很多这样的问题,但大多数答案仅适用于使用入门套件的人,我还阅读了其他一些没有入门工具包的答案,但大多数都不起作用。

This is my login method in the controller:这是我在 controller 中的登录方法:

public function auth()
{
    // validation
    request()->validate([
        'emailOrUsername' => ['required'],
        'password' => ['required']
    ]);

    // Check if the user clicks "remember me" in the login form
    $remember = (request()->remember) ? true : false;

    // If login using email
    if (Auth::attempt(['email' => request()->emailOrUsername, 'password' => request()->password], $remember)) {
        request()->session()->regenerate();
        return redirect()->intended('/dashboard');
    }
    // If login using username
    else if (Auth::attempt(['username' => request()->emailOrUsername, 'password' => request()->password], $remember)) {
        request()->session()->regenerate();
        return redirect()->intended('/dashboard');
    } 
    // If incorrect credentials
    else {
        return back()->with('errorAlert', 'Maaf, email/username atau password yang anda masukkan salah');
    }
}

I also noticed that it seems the default cookie duration for "remember me" is set in the Illuminate\Auth\SessionGuard namespace (but I didn't find the explanation in the official laravel documentation), I see that class has a setRememberDuration() method to change the duration of the "remember me" cookie, but I don't know how to properly call it, I've used Auth::setRememberDuration(1000) but it doesn't work.我还注意到“记住我”的默认 cookie 持续时间似乎是在Illuminate\Auth\SessionGuard命名空间中设置的(但我在官方 laravel 文档中没有找到解释),我看到 class 有一个setRememberDuration()更改“记住我”cookie持续时间的方法,但我不知道如何正确调用它,我使用了Auth::setRememberDuration(1000)但它不起作用。 Is there any other way to set the "remember me" cookie duration using that method?有没有其他方法可以使用该方法设置“记住我”cookie 持续时间? Or is there another way to change the duration without using that method?还是有另一种方法可以在不使用该方法的情况下更改持续时间?

You can set it in config/auth.php:您可以在 config/auth.php 中设置它:

'guards' => [
    'web'     => [
        'driver'   => 'session',
        'provider' => 'users',
        'remember' => now()->addDays(7)->diffInMinutes(),
    ]
],

it's then used by the AuthManager:然后由 AuthManager 使用:

if (isset($config['remember'])) {
    $guard->setRememberDuration($config['remember']);
}

edit:编辑:

For future readers, this answers only work from Laravel 8.65.0对于未来的读者,此答案仅适用于 Laravel 8.65.0

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

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