Can anybody help me with cakephp 2.4.2 auth using blowfish, I'm new to cakephp auth so I've googled it up but didn't find any solution for my problem.
Here is my code
For App Controller
public $components = array(
'Session',
'RequestHandler',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'passwordHasher' => 'Blowfish'
)
)
)
);
For Model
public function beforeSave($options = array()){
if (isset($this->data[$this->name]['password'])) {
$this->data[$this->name]['password'] = Security::hash($this->data[$this->alias]['password'], 'blowfish');
}
return true;
}
For Controller
if ($this->Auth->login()) {
$this->redirect(array('controller' => 'admins', 'action' => 'dashboard', 'builder' => true));
} else {
$this->Session->write('flash', array('You Have entered wrong username or password.', 'failure'));
$this->redirect(array('controller' => 'users', 'action' => 'login', 'builder' => true));
}
For blowfish you need to provide a salt, that is a bcrypt salt
from docs
http://book.cakephp.org/2.0/en/core-utility-libraries/security.html#Security::hash
// Create a hash using bcrypt
Security::setHash('blowfish');
$salt = Security::hash(Configure::read('Security.salt'));
// $salt is a previously generated bcrypt salt.
$passwordHash = Security::hash($password, 'blowfish', $salt);
I would recommend using separate salt for each user/password, in that case instead of using security salt for creating the bcrypt salt, use some random string, and then save the salt in your database along with password hash.
during user login use this scenario
1) fetch the salt and the password hash from database
2) using salt and the plain text password provided by user during login to generate the password hash
3) compare newly generated password hash with what was fetched from the db.
4) if they match login the user, otherwise show error
for login use if ($this->Auth->login($userData)) { and $userData should be array like
array ('username' => 'the_username', 'password' => 'the_password');
authentication:
$userData = $this->User->findByEmail('myEmail#gmail.com', array('username', 'password', 'salt'));
$passwordHash = Security::hash($userPlainTextPassword, 'blowfish', $userData['User']['salt']);
if ($passwordHash == $userData['User']['password']) {
if ( $this->Auth->login($userData['User'])) {
// ok
} else {
// smth wrong
}
} else {
// wrong username or password
}
btw, for comparing the hashes you better use standard time comparison, read more here
https://crackstation.net/hashing-security.htm#properhashing
Try this in your AppController:
$this->Auth->authenticate = array(
AuthComponent::ALL => array(
'userModel' => 'User',
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'scope' => $user_scope,
), 'Form'=> array(
'passwordHasher' => 'Blowfish'
)
);
Related
I'm using the cakephp 4.2.6 with the cakedc/users plugin. I'd like to automatically login the user after registration without the need to first activate the account by clicking on the link in e-mail.
My idea is to creating an Event-Listener and listening to the Users.Global.afterRegister Event, but then I don't know how to login the user with the new Authentication.
this is what I ended up with and it seems to work so far:
<?php
namespace App\Event;
use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceInterface;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Middleware\AuthenticationMiddleware;
use Psr\Http\Message\ServerRequestInterface;
use Cake\Event\EventListenerInterface;
use Cake\Datasource\FactoryLocator;
use Cake\Log\Log;
class UserEventListener implements EventListenerInterface
{
public function implementedEvents(): array
{
return [
'Users.Global.afterRegister' => 'autoLogin',
];
}
public function autoLogin($event)
{
$user = $usersTable->get($event->getData('user')->id);
$request = $event->getSubject()->getRequest();
$response = $event->getSubject()->getResponse();
$authenticationService = $this->getAuthenticationService($request);
$authenticationService->persistIdentity($request, $response, $user);
}
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$authenticationService = new AuthenticationService([
'unauthenticatedRedirect' => \Cake\Routing\Router::url([
'controller' => 'Users',
'action' => 'login',
'plugin' => null,
'prefix' => null
]),
'queryParam' => 'redirect',
]);
// Load identifiers, ensure we check email and password fields
$authenticationService->loadIdentifier('Authentication.Password', [
'fields' => [
'username' => 'email',
'password' => 'password',
]
]);
// Load the authenticators, you want session first
$authenticationService->loadAuthenticator('Authentication.Session');
// Configure form data check to pick email and password
$authenticationService->loadAuthenticator('Authentication.Form', [
'fields' => [
'username' => 'email',
'password' => 'password',
],
'loginUrl' => \Cake\Routing\Router::url([
'controller' => 'Users',
'action' => 'login',
'plugin' => null,
'prefix' => null
]),
]);
return $authenticationService;
}
}
There is a similar use case covered in the plugin documentation https://github.com/CakeDC/users/blob/master/Docs/Documentation/Events.md
Your approach looks correct to me, using the afterRegister event to create the listener in a controller where you have access to the Authenticatication component,
// note this example is handling auto-login after the user validated the email sent (click the validation token link sent to his email address)
EventManager::instance()->on(
\CakeDC\Users\Plugin::EVENT_AFTER_EMAIL_TOKEN_VALIDATION,
function($event){
$users = $this->getTableLocator()->get('Users');
$user = $users->get($event->getData('user')->id);
$this->Authentication->setIdentity($user);
}
);
or using the request to retrieve the authentication service and set the identity like it's done here https://github.com/cakephp/authentication/blob/master/src/Controller/Component/AuthenticationComponent.php#L273
I am working on a Cakephp 2.3 on a very big project and I'm about to launch my site worldwide.
I have a login system on my app. I am sharing my code because I want to make sure if I am coding right or not ... and also any check for any functions missing or if any advice of adding something or removing something in the code would be greatly appreciated. And also comment in security perspective too...
Do tell me some tips of making my website faster.. for example how to write faster queries or remove unwanted from this blabla
class UsersController extends AppController
{
public $components = array('Cookie');
public function beforeFilter()
{
parent::beforeFilter();
App::uses('Utility', 'Utility');
$this->Auth->allow('index');
$this->Security->requireSecure('login'); // for security
$this->Auth->authenticate = array(
'Authenticate.Cookie' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'userModel' => 'User',
'scope' => array(
'User.active' => 1
)
),
'Authenticate.MultiColumn' => array(
'fields' => array(
'username' => 'email',
'password' => 'password'
),
'columns' => array(
'email',
'mobileNo'
),
'userModel' => 'User'
)
);
}
public function index()
{
$this->layout = 'logindefault';
if (!$this->Auth->login() || !$this->Auth->loggedIn()) {
$this->redirect(array(
'controller' => 'users',
'action' => 'login'
));
} else {
$this->redirect(array(
'controller' => 'users',
'action' => 'dashboard'
));
}
}
public function login()
{
$this->layout = 'logindefault';
$this->set('title_for_layout', 'Account Login');
if ($this->Auth->login() || $this->Auth->loggedIn()) {
$lastLogin = $this->Auth->User('lastLogin');
if ($lastLogin != null) {
$this->redirect($this->Auth->redirect());
} else {
$this->redirect(array(
'controller' => 'Userinfo',
'action' => 'gettingstarted'
));
}
} else {
if ($this->request->is('post')) {
$mobileNo = $this->request->data['User']['email'];
$mobileNo = Utility::addPlusToMobileNo($mobileNo);
$this->request->data['User']['email'] = $mobileNo;
if ($this->Auth->login() || $this->Auth->loggedIn()) {
if ($this->Session->check('Auth.User')) {
$this->_setCookie($this->Auth->user('idUser'));
$lastLogin = $this->Auth->User('lastLogin');
if ($lastLogin != null) {
$this->redirect(array(
'controller' => 'users',
'action' => 'dashboard'
));
} else {
$this->redirect(array(
'controller' => 'Userinfo',
'action' => 'gettingstarted'
));
}
}
} else {
$this->Session->setFlash('Incorrect Email/Password Combination');
}
}
}
}
protected function _setCookie($id)
{
if (!$this->request->data('User.remember_me')) {
return false;
}
$data = array(
'username' => $this->request->data('User.email'),
'password' => $this->request->data('User.password')
);
$this->Cookie->write('User', $data, true, '1 week');
return true;
}
public function logout()
{
$this->Cookie->delete('User');
$this->redirect($this->Auth->logout());
}
Looks like you're already using the SecurityComponent if you want to secure your app use it everywhere. For AJAX forms white list only the fields you need, dont disable the component!
Put App::uses('Utility', 'Utility'); on top of the file
$mobileNo = Utility::addPlusToMobileNo($mobileNo); should happen in the model beforeSave()
If this is supposed to be used world wide I assume you want translations, this is missing the translation method call __() setFlash('Incorrect Email/Password Combination');
Most of the code CAN and should go into the model layer
Are there unit tests? If not add unit tests, specially test validation of data and false data input. You want ~85%+ Code Coverage for unit tests.
You're not following the CakePHP coding standards
There is no way to tell you more than this without being able to access the whole app code and doing a code review (I could do that). For queries, always just query the data you need, check the generated SQL queries, use DebugKit to check the query times to find slow querys and slowly rendering pages.
What I did
I used this part of the Cookbook to create my authentication: Link
After i was finished, i changed the fields to email and password (in AppController.php):
public function beforeFilter() {
$this->Auth->allow('index');
$this->Auth->fields = array('username' => 'email', 'password' => 'password');
}
What happened
The login form always said that my password/email combination was not correct.
After a while searching and trying stuff, i added "$this->request->data" to the Auth->login() parameter in the login() function of the UsersController:
public function login(){
$this->layout = 'login';
if ($this->request->is('post')){
if ($this->Auth->login($this->request->data)){
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Ongeldig email adres of wachtwoord. Probeer het AUB opnieuw'));
}
}
}
This worked, but now i can't use "$user['id']" to get the loggedin users id. It says that it doesn't know the $user variable.
What I expected to happen
In the first place, it should have logged the user in without me adding the parameter. And second, it should have printed the loggedin user's id.
I hope someone can help me with the problem.
Thanks in advance!
fields is now in the authenticate array:
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email', ...)
)
)
see
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#configuring-authentication-handlers
either with
$this->Auth->authenticate = ...
or
public $components = array(
'Auth' => array(
'authenticate' => ...
)
);
but, as PHP freelancer stated, this is well documented.
what cookbook version did you use? the 2.x one?
I have tried most if not all tutorials for CakePHP 1.3 on their Auth method and non seem to work on CakePHP 2.0.
I can add users, hash the passwords, but the login feature does not work. It just refreshes the page when I click on login. No errors, no nothing.
I would appreciate some tips please and thank you for reading my question.
This my code
public function login()
{
if ($this->request->is('post') )
{
if( $this->Auth->login() )
{
// the redirect() function in the Auth class redirects us
// to the url we set up in the AppController.
return $this->redirect( $this->Auth->redirect());
}
else
{
$this->Session->setFlash(__('Email or password is incorrect',true));
}
}
}
Thanks,
Mahadeva Prasad
First of all check how you have hash the password.Also check the field length in database.
Preferred - varchar(255)
The password will be hash as follows.
class User extends AppModel {
public function beforeSave($options = array()) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
return true;
}
}
Also as you are using FormAuthenticate try using this when declaring component.
public $components = array(
'Auth' => array(
'loginAction' => array(
'controller' => 'users',
'action' => 'login',
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'username')
)
)
)
);
For more information refer http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
The web app is working great except for auth manual calls. I've been struggling with this for days. In my sample code I have temporarily rewritten the cookie to narrow down the cause. Here is my app controller snip:
App::import('Sanitize');
//uses('sanitize');
class AppController extends Controller {
var $components = array('Clean','Acl', 'Auth', 'Session', 'RequestHandler', 'Cookie', /* 'DebugKit.Toolbar' */);
var $helpers = array('uiNav','Flash','Html', 'Form', 'Session','Javascript','Ajax','Js' => array('Jquery'), 'Time','Js');
function beforeFilter() {
//Configure AuthComponent
$this->Auth->authorize = 'actions';
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'view');
$this->Auth->actionPath = 'controllers/';
$this->Auth->autoRedirect = false;
$this->Auth->allowedActions = array('display');
if(!$this->Auth->user()){
//$cookie = $this->Cookie->read('Auth.User');
$cookie = array('username' => 'chris22', 'password' => 'stuff');
if (!is_null($cookie)) {
$this->set('checking_cookie',$cookie);
if ($this->Auth->login($cookie)) {
$this->set('cookie_message','cookie validates!');
// Clear auth message, just in case we use it.
$this->Session->delete('Message.auth');
/* $this->redirect($this->Auth->redirect()); */
}
}
}
}
}
As you can see I'm just plugging the user name and password into $this->Auth->login and it's not working!!
I don't know if my user controller is relevent, but here is the login function for that too:
function login() {
if ($this->Auth->user()) {
if (!empty($this->data) && $this->data['User']['remember_me'] && isset($this->data['User']['password'])) {
$cookie = array();
$cookie['username'] = $this->data['User']['username'];
$cookie['password'] = $this->data['User']['password'];
$this->Cookie->write('Auth.User', $cookie, true, '+1 month');
//unset($this->data['User']['remember_me']);
$this->set('cookie-00', 'setting cookie.');
}else{ $this->set('cookie_message', 'not setting cookie.');}
$this->redirect($this->Auth->redirect());
}
}
Thanks!
EDIT - 1 - I think I know why this is not working for you.
Reason 1: $this->Auth->login takes data in the form of
array(
'User'=>array(
'username'=>'myusername',
'password'=>'mypassword'
)
)
Reason 2: $this->Auth->login does NOT hash the password.
You must send the password exactly as it appears in the database.
EVERYTHING BELOW THIS LINE IS POSSIBLE BUT NOT LIKELY IN THIS CASE:
Are you sure that when you originally created the username and password, the hashes were setup?
To check that your hashes match look at your users table with phpmyadmin or mysql workbench and find the password field for the user chris22
Compare that entry to your current hashing. To check your current hash, put the code below somewhere in a controller function (index) and navigate there.
debug(Security::hash('stuff'));
exit;
I hope this helps!
Make sure the fields are correctly assigned in the Auth component.
if you use different field names than username & password to connect, you must declare them in your controller like this way :
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email', 'password' => 'mot_de_passe')
)
)
)