How to change duration of "remember me" cookie in laravel 9? - php

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.
This is my login method in the 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. Is there any other way to set the "remember me" cookie duration using that method? Or is there another way to change the duration without using that method?

You can set it in config/auth.php :
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
'remember' => now()->addDays(7)->diffInMinutes(),
]
],
it's then used by the AuthManager :
if (isset($config['remember'])) {
$guard->setRememberDuration($config['remember']);
}
edit:
For future readers, this answers only work from Laravel 8.65.0

Related

cakePHP 4 how to change session.cookie_lifetime

I have time in seconds when the session should end. If the user has not selected the checkbox "remember_me" - the session will last 2 hours. When the checkbox is selected - should last - 48 hours. I have a loginСontroller, where I react - to the login result and if the validation is successful and checkbox = "on" you need to change the session time. I tried to change by looking at the documentation, and spent a lot of time looking for a solution. Maybe someone can help me. Thank you very much in advance[enter image description here]
here is my file config/app.php
'Session' => [
'defaults' => 'php',
'ini' => [
'session.cookie_lifetime' => 7200,
]
],
and here is my loginController
`public function index()
{
$this->viewBuilder()->setLayout('main');
$this->set("title", "");
$this->set("description", "description");
$this->request->allowMethod(['get', 'post']);
$result = $this->Authentication->getResult();
// regardless of POST or GET, redirect if user is logged in
if ($result->isValid()) {
if ($this->request->getData('remember') == 'on') {
///// the solution should be here
}
$redirect = [
'controller' => 'Main',
'action' => 'index',
];
return $this->redirect($redirect);
}
// display error if user submitted and authentication failed
if ($this->request->is('post') && !$result->isValid()) {
$this->Flash->saved_error(__('Invalid email or password'));
}
}`
You most likely shouldn't do it that way, your controller code shouldn't have to know about such details if it can be avoided.
The authentication plugin ships with a cookie based authenticator that you can use in addition to the session authenticator, that way you can extend authentication beyond the default session lifetime, I'd suggest that you look into that instead.
$service->loadAuthenticator('Authentication.Cookie', [
'fields' => $fields,
'loginUrl' => $loginUrl,
'cookie' => [
// cookie expires in 2 days from now
'expires' => \Cake\Chronos\Chronos::now()->addDays(2)
],
]);
By default the authenticator looks up a field named remember_me, so either rename that in your template, like:
echo $this->Form->control('remember_me', ['type' => 'checkbox']);
or configure the authenticator's rememberMeField option with the custom field name that you're using in your form.
See also
Authentication Cookbook > Authenticators > Cookie Authenticator

Cakephp Identify user using REST API

I'm developing an API for an application that I'm creating. This application will get all the information from this API (first will auth the user, then get information)
Right now, I'm trying to make the user send a username and password to the API, it validates the information and returns if it's "ok" or "not", very simple to start only. I know all the security involved in this, just need to get this working.
Already managed to send the username and passsword on the API Side (and i'm 100% sure that the data is correctly saved). Though, when I call
$this->Auth->identify($this->request->data);
It always returns false to me (already tried with parameters and without, result is the same).
I'm using the HttpRequester, firefox plugin, to send information.
I've did a debug of $this->request->data to see if the information is correct, and it is. Can't do a find on database since the password is being hashed.
The database password field is a varchar with 300 length (already tried with 255, also no work)
Thanks for the help
EDIT:
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
],
]
]);
if($this->request->is('POST')){
//debug($this->request->data);
$user = $this->Auth->identify($this->request->data);
}
Users Table:
protected $_accessible = [
'*' => true,
];
/**
* Hash password
*
*/
protected function _setPassword($password)
{
return (new DefaultPasswordHasher)->hash($password);
}
protected function _getFullName()
{
if(isset($this->_properties['full_name'])){
return ucwords(mb_strtolower($this->_properties['full_name']));
}
}
ps: Also tried doing the following (replacing the variables form post, but also no luck)
$this->request->data['username'] = "xxxx";
$this->request->data['password'] = "zzzz";
Problem is here
'Form' => [
'fields' => [
'username' => 'email', //email is your database field
'password' => 'password' // password is your database field name
]
],
Your code should be
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
]
],
Details check Configuring Authentication Handlers

Laravel authentication model change

I have two tables for admin and client with two different login method for each type of user.
I use attempt() method for admin already. I am trying to create JWTAuthentication for clients. At this moment when i am trying to authenticate client login , laravel queries inside admin table while I want it to query inside client table. I tried to set config to specifically look into client model. But it is still looking into Admin.
How do i tell laravel to avoid looking into admin table when client is trying to login?
if($dbPass==$password)
{
//find secret api key and send it to curl
//$this->callTeamworkApi($query->secretApiKey);
//set session
//JWT authenticate
//$credentials = ["email"=>$email,"password"=>$password];
//$credentials = $request->all('email','password');
$credentials =[];
$credentials['email'] = $email;
$credentials['password'] = $request->password;
try{
\Config::set('auth.model', 'Client');
\Config::set( 'auth.table' , 'clients' );
if( ! $token = JWTAuth::attempt($credentials))
{
return response()->json([
'response' => 'Some error with user credentials'
]);
}else{
// $request->session()->put('secretApiKey', $query->secretApiKey);
// $request->session()->put('userEmail', $sessionEmail);
// $request->session()->put('userId', $sessionId);
// $request->session()->put('userName', $sessionName);
// $request->session()->put('timeCreated', $timeCreated);
//find user details and put them inside session array
$msg = "Login_checked";
return response()->json(["token"=>compact('token'), "msg"=> $msg]);
}
}catch(JWTExceptions $err){
return response()->json(['response'=>$err]);
}
}else{
$msg = "Password_wrong";
}
All authentication drivers have a user provider. This defines how the users are actually retrieved out of your database or other storage mechanisms used by this application to persist your user's data.
If you have multiple user tables or models you should configure multiple
sources which represent each model / table.
this should be done in config/auth.php file.
'providers' => [
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
],
This works in Laravel 5, I'm not sure about version 4 and below.

CakePHP doesn't set any cookies and session after changing server

I have an application based on CakePHP version 3.2.10. I'm totally new in CakePHP so sorry if it is a banal problem. In my application I use CSRF component and Auth component configured in this way:
$this->loadComponent('Auth', [
'authorize'=> 'Controller',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
'scope' => [
'Users.active' => 1,
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'logoutAction' => [
'controller' => 'Users',
'action' => 'logout'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'index'
],
'unauthorizedRedirect' => '/', // $this->referer()
]);
and login action like
public function login()
{
$this->set('title', 'Logowanie');
$this->set('bodyclass', 'main-page');
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
if($user['blocked'] == 0) {
$this->Auth->setUser($user);
if ($this->Auth->user('role') == 'admin')
return $this->redirect(['controller' => 'Admin', 'action' => 'index']);
return $this->redirect($this->Auth->redirectUrl());
}
else{
$this->Flash->error('Konto zostało zablokowane przez administratora serwisu. Skontaktuj się z Biurem Obsługi.');
}
} else $this->Flash->error('Błędne dane logowania. Spróbuj ponownie.');
}
}
Now the problem:
Few days ago I changed server where application is running, and after changing it logging in stopped working. After clicking login there is a message CSRF Token cookie is missing. To test if the component is the problem i disabled csrf and try again then white screen appears and nothing happen if i refresh page i'm not logged in. I checked the working version and not working version and realized that Cake not store any cookies on new server, while on old there is everything ok and cookies are set.
After few researches i found out that not only cookies not work but all sessions. I try to dump $_SEESION but it shows something only right after calling $this->Auth->setUser($user), and nowhere else. So i look through some solutions and find that there is a setting in config/app.php to set up the session:
'Session' => [
'defaults' => 'php',
],
And read that when set in that way the session is stored in default php dir. So i changed it to cake(even make a dir sessions in tmp folder and added 777 permissions). But the problem was not solved. I have no idea why it not work. I tried setting cookiePath and other settings i Session config, but it still not work.
I think that this may be the server problem(permissions). So few words about servers: Old server where everything was working was my private server(i have full access), new server(or maybe virtual server/host) is on one of hosting companies(home.pl) where i have almost no privileges to configure.
Make sure you follow these steps:
//For Set
var $var = array('Cookie');
//For Write
$this->Cookie->write('YOUR DESIRED NAME', cookieData, $expires = null);
//For Read
$this->Cookie->read('YOUR DESIRED NAME');
Check in your Conroller code should be in src/Controller/AppController.php for below points
1) have you loaded cookie component properly in initialize() or beforeFilter() method?
2) do you have configured domain and path in your cookie configuration using $this->Cookie->configKey(), if Yes, then change domain to new domain or remove domain configuration.
3) delete cache folders for model and persistence from tmp folder
For more information about Cookie refer Document

Laravel 4 session won't persist across page loads

I wanted to integrate the oauth2 server into my laravel 4.1 project. The password flow went pretty well but when writing the authorization code flow I encountered some strange problems with the sessions.
The request to generate leads to this function where filtered for logged in users
Route::get('security/authorize', array('before' => 'check-authorization-params|auth', function()
{
[...]
}));
Guests are redirected to a form to log in
Route::get('security/login', array('before' => 'guest' ,function()
{
return View::make('users.login');
}));
Wich leads to this route where the user should be logged in and redirected to the request he intended to do:
public function login()
{
$creds = array(
'email' => Input::get('email'),
'password'=>Input::get('password')
);
if(Auth::attempt($creds, true))
{
return Redirect::intended('/');
}
return Redirect::to('security/login');
}
The problem is, despite a positive Auth::attempt() I keep being redirected by the auth filter.
I made a few brief tests to check whats wrong by setting and reading session data wich never reached the next request, so i figured out i must have to do with my sessions.
Here's my session config file
<?php
return array(
'driver' => 'database',
'lifetime' => 120,
'expire_on_close' => false,
'files' => storage_path().'/sessions',
'connection' => 'mysql',
'table' => 'sessions',
'lottery' => array(2, 100),
'cookie' => 'laravel_session',
'path' => '/',
'domain' => null,
);
and here are some things I double checked:
database connection is correct and sessions show up in my table
session table fields have the right data types (id - varchar(255), payload - text, last_activity - int(11))
cookies get set
It turned out, that I did not set up the auth identifier in my user model correctly.
Changing it from this
public function getAuthIdentifier()
{
return $this->email;
}
to this
public function getAuthIdentifier()
{
return $this->id;
}
fixed everything.

Categories