Git Product home page Git Product logo

cakephp-remember-me's Introduction

RememberMe authentication adapter plugin for CakePHP

Software License Build Status Codecov Latest Stable Version

This plugin provides an authenticate handler that permanent login by cookie. This plugin use method of issuing a token, instead of set to cookie encrypted username/password.

This library inspired by Barry Jaspan's article "Improved Persistent Login Cookie Best Practice", and Gabriel Birke's libray "https://github.com/gbirke/rememberme".

Installation

You can install this plugin into your CakePHP application using composer.

The recommended way to install composer packages is:

php composer.phar require nojimage/cakephp-remember-me:^5.0

Load the plugin by adding the following statement in your project's src/Application.php:

$this->addPlugin('RememberMe');

or running the console command

bin/cake plugin load RememberMe

Run migration:

bin/cake migrations migrate -p RememberMe

Usage with Authentication plugin

If you're using cakephp/authentication, use RememberMeTokenIdentifier and CookeAuthenticator.

Example load RememberMe's Identifier and Authenticator into the getAuthenticationService hook within Application:

// in your src/Application.php
class Application extends ...
{
    public function getAuthenticationService(...): void
    {
        $service = new AuthenticationService();
        $fields = [
            'username' => 'email',
            'password' => 'password'
        ];
        // ... setup other identifier and authenticator

        // setup RememberMe
        $service->loadIdentifier('RememberMe.RememberMeToken', compact('fields'));
        $service->loadAuthenticator('RememberMe.Cookie', [
            'fields' => $fields,
            'loginUrl' => '/users/login',
        ]);
    }
}

more document for getAuthenticationService, see: Quick Start - CakePHP Authentication 3.x

RememberMe.RememberMeTokenIdentifier options

fields

The fields for the lookup.

default: ['username' => 'username']

    $service->loadIdentifier('RememberMe.RememberMeToken', [
        'fields' => [
            'username' => 'email',
        ],
    ]);

resolver

The identity resolver. If change your Resolver, must extend Authentication\Identifier\Resolver\OrmResolver.

default: 'Authentication.Orm'

    $service->loadIdentifier('RememberMe.RememberMeToken', [
        'resolver' => [
            'className' => 'Authentication.Orm',
            'userModel' => 'Administrators',
        ],
    ]);

tokenStorageModel

A model used for find login cookie tokens.

default: 'RememberMe.RememberMeTokens'

    $service->loadIdentifier('RememberMe.RememberMeToken', [
        'tokenStorageModel' => 'YourTokensModel',
    ]);

userTokenFieldName

A property name when adding token data to identity.

default: 'remember_me_token'

    $service->loadIdentifier('RememberMe.RememberMeToken', [
        'userTokenFieldName' => 'cookie_token',
    ]);

RememberMe.CookeAuthenticator options

loginUrl

The login URL, string or array of URLs. Default is null and all pages will be checked.

default: null

    $service->loadAuthenticator('RememberMe.Cookie', [
        'loginUrl' => '/users/login',
    ]);

urlChecker

The URL checker class or object.

default: 'DefaultUrlChecker'

    $service->loadAuthenticator('RememberMe.Cookie', [
        'loginUrl' => '/users/login',
    ]);

rememberMeField

When this key is input by form authentication, it issues a login cookie.

default: 'remember_me'

    $service->loadAuthenticator('RememberMe.Cookie', [
        'rememberMeField' => 'remember_me',
    ]);

fields

Array that maps username to the specified POST data fields.

default: ['username' => 'username']

    $service->loadAuthenticator('RememberMe.Cookie', [
        'fields' => [
            'username' => 'email',
        ],
    ]);

cookie

Write option for login cookie.

  • name: Cookie name (default: 'rememberMe')
  • expire: Cookie expiration (default: '+30 days')
  • path: Path (default: '/')
  • domain: Domain, (default: '')
  • secure: Secure flag (default: true)
  • httpOnly: Http only flag (default: true)
    $service->loadAuthenticator('RememberMe.Cookie', [
        'cookie' => [
            'name' => 'rememberMe',
            'expires' => '+30 days',
            'secure' => true,
            'httpOnly' => true,
        ],
    ]);

tokenStorageModel

A model used for storing login cookie tokens.

default: 'RememberMe.RememberMeTokens'

    $service->loadAuthenticator('RememberMe.Cookie', [
        'tokenStorageModel' => 'YourTokensModel',
    ]);

always

When this option is set to true, a login cookie is always issued after authentication identified.

default: false

    $service->loadAuthenticator('RememberMe.Cookie', [
        'always' => true,
    ]);

dropExpiredToken

When this option is set to true, drop expired tokens after authentication identified.

default: true

    $service->loadAuthenticator('RememberMe.Cookie', [
        'dropExpiredToken' => false,
    ]);

cakephp-remember-me's People

Contributors

mbglytch avatar nojimage avatar tksmrkm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

tksmrkm moutard3

cakephp-remember-me's Issues

Cookie not decoded

hello
The cookie is saved but not decoded.

The site in https
cakephp 3.6.9 (but same problem with 3.6.7)

The config :

$this->loadComponent('Auth', [
            'authenticate' => [
                'RememberMe.Cookie' => [
                    'userModel' => 'Users',
                    'fields' => ['username' => 'user_login'],
                    'always' => true,
                    //'inputKey' => 'remember_me',

                    'cookie' => [
                        //'name' => 'rememberMe',
                        //'expires' => '+10 days',
                        'secure' => true,
                        'httpOnly' => false,
                    ],

                ],
                'Form' =>[
                    'fields' => ['username' => 'user_login','password' => 'user_pass'],
...

When the user is loged the fist time:

  • there is an entry in the databse
  • a cookie is created

When the user try to reconnect after some time :

  • the cookie is send to the application
  • the cookie is not decoded
    so the user must loggin again

I add some debug in your code (but found no solution to correct it)
1st debug in function checkFields

$cookie = $this->getCookie($request);
Log::write('debug',$cookie);

I can see :

2018-07-30 21:55:57 Debug: Q2FrZQ==.MGE0YTc3MzJjMzhjMzM1ODg5NjU0M2U5NDZjYzU1YWY5ODczOGRkMmEzZTA0NGYzYjk3OGExMzgzODU0YTFkOfZ/eLunwTFYUBZ7SqIPdBr0d
EVIatGD6l8lOLrftHbE+JcgikbUoAQPBQscnsKm21p3FT3TgHiUWxP96nZAJy8=

2nd debug in function checkFields again

$decoded = $this->decodeCookie($cookie);
Log::write('debug',$decoded);

$decoded variable is empty :
2018-07-30 21:55:57 Debug:

Thanks for your help
F.

Unable to set cookie

I have tried to install this plugin, but do not see any cookies getting set. Below is the setup I'm using:

In src/Controller/AppController.php

`
$this->loadComponent('Auth',[

	 'loginRedirect' => [
		    'controller' => 'Users',
		    'action' => 'dashboard'
	    ],
	    'logoutRedirect' => [
		    'controller' => 'Users',
		    'action' => 'login'
	    ],
	    'authenticate' => [
		    'RememberMe.Cookie' => [
			    'userModel' => 'Users',
			    'fields' => ['username' => 'email', 'password' => 'password'],
			    'inputKey' => 'remember_me',
			    'always' => true,
			    'cookie' => [
				    'name' => 'rememberMe',
				    'expires' => '+90 days',
				    'secure' => true,
				    'httpOnly' => true,
			    ],
		    ],
		    'Form' => [
			    'fields' => ['username' => 'email', 'password' => 'password']
		    ]
	    ]
    ]);

`

In src/Template/Users/login.ctp

`

Form->create() ?>
<fieldset>
	<legend><?= __('Please enter your username and password') ?></legend>
	<?= $this->Form->control('email') ?>
	<?= $this->Form->control('password') ?>
	<?= $this->Form->control('remember_me', ['type' => 'checkbox']) ?>
</fieldset>
<br />
<?= $this->Form->button(__('Login'), ['class' => 'btn btn-success']); ?>


<?= $this->Form->end() ?>

`

When I login (and check the remember me checkbox, I see a new token in the remember_me_tokens with the foreign_id matching my user_id. However, when I examine the cookies, I see nothing set other than the csrfToken.

I must be missing something obvious here, but not seeing it.

CakePHP 3.7 on PHP 7.0.33

AppController AuthComponent

In AppController
when i replace

$this->loadComponent('Auth', [
            'authorize' => 'Controller',
            'storage' => 'Session',
        ]);

to

$this->loadComponent('Auth', [
        'authenticate' => [
            'RememberMe.Cookie' => [
                'userModel' => 'Users',
                'fields' => ['username' => 'email'],
                'inputKey' => 'remember_me',
            ],
            // ... other authenticater config
        ],
        // ... other auth component config
    ]);

it fails to identify the user.

Cookie not saved

Hey, I just installed this plugin but I can't manage to make it work.

From what I manage to debug, $this->setLoginTokenToCookie($authComponent->response, $user, $token); is returning the cookie, but it's not set after login.

The token is well saved.

$this->loadComponent('Auth', [
            'authorize' => 'Controller',
            'loginAction' => [
                'plugin' => null,
                'prefix' => false,
                'controller' => 'Users',
                'action' => 'login'
            ],
            'loginRedirect' => '/',
            'logoutRedirect' => '/',
            'authenticate' => [
                'RememberMe.Cookie' => [
                    'always' => true,
                ],
                'Form',
            ]
        ]);

Hostinger Conflict

Hostinger conflict, when hostinger git detect this, it suddenly returns an error: install: Command unexpectedly terminated without error message.

_matchingData not selected

In CookieAuthenticate::findUserAndTokenBySeries $user->_matchingData is not present in the result of the query.

In my app i use a custom finder to find the user. In this finder i use query builder to select only what i need.
$query->select(['id', 'email', 'password', 'role', 'member_id', 'is_secret', 'secret'])

I fixed this using another custom finder for RememberMe.Cookie Auth specifying this.
$query->select(TableRegistry::get('RememberMe.RememberMeTokens'))

Maybe you can add this to CookieAuthenticate::findUserAndTokenBySeries line 260
$query->select($this->getTokensTable())

More details in the README.md

Hey hi!

Thank you very much for the work you've done here! I juste have one or two questions on how to use your plugin. I installed it via composer and loaded it from the Auth Component.

$this->loadComponent('Auth', [
    'authenticate' => [
        'Form' => [
            'finder' => 'auth'
        ],
        'RememberMe.Cookie' => [
            'cookie' => [
                'name'     => 'rememberMe',
                'expires'  => '+30 days',
                'secure'   => true,
                'httpOnly' => true,
            ],
        ],
    ],
    'loginAction' => [
        'controller' => 'Users',
        'action'     => 'login',
        'prefix'     => false
    ],
    'loginRedirect' => [
        'controller' => 'Pages',
        'action'     => 'home',
        'prefix'     => false
    ],
    'logoutRedirect' => [
        'controller' => 'Pages',
        'action'     => 'home',
        'prefix'     => false
    ],
    'authError' => __("Vous n'êtes pas autorisé à accéder à cette section."),
    'authorize' => ['Controller'], 
]);

Plus in my login form I added the following lines :

<?= $this->Form->create() ?>
    <?= $this->Form->control('username', ['label' => '', 'placeholder' => __('Pseudonyme')]); ?>
    <?= $this->Form->control('password', ['label' => '', 'placeholder' => __('Mot de passe')]); ?>
	<?= $this->Form->control('remember_me', ['type' => 'checkbox', 'label' => __("Se souvenir de moi ?")]); ?>	
	<?= $this->Form->button(__('Connexion')); ?>
<?= $this->Form->end() ?>

Is there anything else that is needed to make the plugin works? After a login, nothing happends and there is no cookie generated.

Maybe I missed something? It would be great if you could add some informations regarding the installation.

I'm using php 7.2.7 and Cakephp 3.7

document.cookie
<- ""

Remember me not working

Hi there, I am looking for some guidance. I have a website that uses the tinyauth plugin. I expect everything to work the same. This is some of my code:

$this->loadComponent('TinyAuth.Auth', [
            'autoClearCache' => true,
            'authorize' => [
                'TinyAuth.Tiny' => [
                   'roleColumn' => 'role_id',
                   'rolesTable' => 'Roles',
                ]
            ],
            'authenticate' => [
                'RememberMe.Cookie' => [
                    'userModel' => 'Users',
                    'fields' => ['username' => 'email', 'password' => 'password'],
                    'inputKey' => 'remember_me',
                    'cookie' => [
                        'name' => 'rememberMe',
                        'expires' => '+90 days',
                        'secure' => true,
                        'httpOnly' => true,
                    ],
                ],
                'Form' => [
                    'fields' => ['username' => 'email', 'password' => 'password'],
                    'finder' => 'auth'
                ],
            ],
            'loginAction' =>[
                'controller' => 'Login',
                'action' => 'index',
                'prefix'    => false,
                'plugin' => false
            ],
            'authError' => __('Log in to access this page.'),
            'logoutRedirect' => [
                'controller' => 'Login',
                'action' => 'index',
                'prefix'=> false,
                'plugin' => false
            ],
            'unauthorizedRedirect' => [
                'controller' => 'Login',
                'action' => 'index',
                'prefix'=> false,
                'plugin' => false
            ]
        ]);

A cookie gets set and is stored in the database. However after some time when my session has expired and return to the website I am logged out, even though the rememberMe cookie is still set. I am kinda out of ideas on how to fix it. Do you see any issues?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.