In one laravel project, I would have two auth method:
API client authentication (to check if client can query the API) with dedicated eloquent model (something like APIUser)
User authentication (to check user credential) with another dedicated model (Something User)
I would like to authenticate through first auth system then check a user credential through second auth system. Example :
curl -u a:b myapi/?user=c&pass=d
So a&b are login and password for API client authentication and c&d are login and password for user authentication. What can be the best way to do that: create a multi-auth system ? or consider only one system is for auth, the other is just querying database ? or something else ? (hope my question is clear enough, I can edit if you need)
Multiauth works like a build-in laravel auth, but allow few independent auth sessions (you can login on first, second or both accounts).
Use Ollieread's MultiAuth extension for Laravel. It sets everything up for you. Just open up the file app/config/auth.php and replace this array:
return array(
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users',
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
with
return array(
'multi' => array(
'admin' => array(
'driver' => 'eloquent',
'model' => 'Admin'
),
'user' => array(
'driver' => 'database',
'table' => 'users'
)
),
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
Of course, you can add as many as you want. Then copy paste the default User.php model for your Admin.php table.
Related
I have added the authentication plugin and changed the code as per the CakePHP 4 documentation (https://book.cakephp.org/4/en/tutorials-and-examples/cms/authentication.html). by default they using "users" table for authenticating. how can I change the default "users" table to the table "clients"?
Thank You.
Using Authentication ORM to solve this issue
Edit under src/Application.php
// Load identifiers, ensure we check email and password fields
$authenticationService->loadIdentifier('Authentication.Password', [
'fields' => [
'username' => 'staff_email',
'password' => 'staff_password',
],
'resolver'=>[
'className'=>'Authentication.Orm',
'userModel' => 'myStaffs',
],
]);
In src/Application.php in the getAuthenticationService function try to add the following:
$authenticationService->loadAuthenticator('Authentication.Form', [
'fields' => [
'username' => 'email',
'password' => 'password',
],
'userModel' => 'Clients',
'loginUrl' => '/clients/login',
]);
I'm using CakePHP 2.10.9 version and trying to use token-based authentication instead of session-based authentication.
I couldn't find any information on how to use JWT with CakePHP 2.x.
Here is what I have tried so far. As a first step, I downloaded the plugin t73biz/cakephp2-jwt-auth and added this into the folder app/Plugin/JwtAuth. As mentioned in the usage(https://github.com/t73biz/cakephp2-jwt-auth), I added below configuration in the app/Controller/AppController.php
var $components = array(
'Auth' => array(
'authenticate' => array(
'JwtAuth.JwtToken' => array(
'fields' => array(
'username' => 'username',
'password' => 'password',
'token' => 'public_key',
),
'parameter' => '_token',
'userModel' => 'User',
'scope' => array('User.active' => 1),
'pepper' => 'sneezing',
),
),
),'Session','RequestHandler','Email','Flash');
From my past experience with Plugin's, I knew I'm supposed to include the plugin in bootstrap.php.
CakePlugin::load('JwtAuth');
I don't know what am I supposed to do after this. Could someone guide me?
I think you didn't read the the Authentication part
=> The query string parameter defined as parameter in the config array (defaults to _token)
=>The contents of the header defined as header in the config array (defaults to X_JSON_WEB_TOKEN)
It means when you access any method then you have to pass the JWT toekn with query params or Header request.
Sample Query params:
http://example.com/users/add?_token=THEJWTWEVTOKEN
I configure a Auth component to "Admin page", using the users model. But now, I also want create/configure a Auth to the clients. I try "rewrite" the inialize()
//This is in my ClientsController.php
public function initialize()
{
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'userModel' => 'clients',
'fields' => ['username' => 'client_email', 'password' => 'client_password']
]
],
'loginRedirect' => [
'controller' => 'Clients',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Clients',
'action' => 'login'
],
]);
}
With this, I receive this log(if uses parent::initalize() receive the same)
[RuntimeException] The "Auth" alias has already been loaded with the following config: array (...
I not want create a "Auth" manualy. How to use more of one Auth?
Thanks....
Reconfigure
You don't necessarily need to use multiple auth component instances, you can simply reconfigure it in the extended controller, using the components config() method, something along the lines of:
public function initialize()
{
parent::initialize();
// ...
$this->Auth->config(
[
'authenticate' => [
'Form' => [
'userModel' => 'clients',
'fields' => [
'username' => 'client_email',
'password' => 'client_password'
]
]
],
'loginRedirect' => [
'controller' => 'Clients',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Clients',
'action' => 'login'
],
'storage' => [
'className' => 'Session',
'key' => 'Auth.Client'
]
],
null,
false
);
}
Note the use of the storage option, you should define a different key here (the default is Auth.User), otherwise an authenticated client might be able to access the admin area and vice versa, as the user data would get stored in the same session key!
Use aliasing
You could use multiple auth components if required, to do so you'd have to use aliasing, so that the components don't try to override each other:
$this->loadComponent('ClientAuth', [
'className' => 'Auth',
// ....
]);
Don't forget to use a different session key in this case too!
You'd access that component instance as $this->ClientAuth accordingly, and you may have to allow access to the login() method via $this->Auth, ie. in ClientsController::initialize() or beforeFilter() do:
$this->Auth->allow('login');
There might be further side-effects, so be careful.
See also
Cookbook > Controllers > Components > Authentication > Configuration options
Cookbook > Controllers > Components > Aliasing Components
I am trying to setup Yii2 advanced like a traditional user/admin system. Frontend would be /user and backend would be /admin, and would use their respective table in the database (user and admin). I have not renamed frontend and backend to user and admin yet..
Using migrate generated the 'user' table, with all it's fields. I registered to create a new user, all that works perfect. I then copied the 'user' table and named it 'admin', and changed the username to admin. I can change the password, or truncate it, register new admin user, then remove the registration from the backend later. The admin table in the db itself isn't the issue as I am not getting that far when I reach the error..
I have setup and used Yii2 advanced just fine on the frontend (user) side of it. Of course, you have Yii::$app->user and it works just fine on the frontend. I can login, it uses the 'users' table. Frontend works great...
Now on the backend (admin) I need it to use the 'admin' table. I know you specify the table to use in the model. I copied /common/models/User.php and have /common/models/Admin.php and updated the function to use the 'admin' table instead.
I also copied /vendor/yiisoft/yii2/web/User.php and put it in /common/models/web/Admin.php (and renamed the name of the class from User to Admin)
Then I edited the /backend/config/main.php to reflect the changes for Admin (class and identityClass).
/backend/config/main.php
'components' => [
'admin' => [
'identityClass' => 'common\models\Admin',
'class' => 'common\models\web\Admin',
'enableAutoLogin' => true,
],
],
/common/models/web/Admin.php
class Admin extends Component { ... }
/common/models/Admin.php
class Admin extends ActiveRecord implements IdentityInterface {
public static function tableName()
{
return '{{%admin}}';
}
}
Error: User::identityClass must be set. <-- As you can see, it's still references the User model some how...
Also, when I get this setup, would I use Yii::$app->admin instead of Yii::$app->user ? Like for checking if they are logged in using isGuest.
I want to be sure that a user can't login to frontend, then manually go to backend and be logged in!
I have solved this :)
You have to edit the main config of each (frontend and backend) and specify the 'identityClass' for the user component, and add 'session' and 'request' to the list.
Example of frontend config:
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_frontendUser', // unique for frontend
]
],
'session' => [
'name' => 'PHPFRONTSESSID',
'savePath' => sys_get_temp_dir(),
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '[RANDOM KEY HERE]',
'csrfParam' => '_frontendCSRF',
],
],
Example of backend config:
'components' => [
'user' => [
'identityClass' => 'common\models\Admin',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_backendUser', // unique for backend
]
],
'session' => [
'name' => 'PHPBACKSESSID',
'savePath' => sys_get_temp_dir(),
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '[DIFFERENT UNIQUE KEY]',
'csrfParam' => '_backendCSRF',
],
],
For a more detailed guide, you can read the wiki I created.
Wiki: [Guide] How to actually separate Frontend and Backend on Yii2 Advanced
Hai i am new to the cakephp.I have designed login page and signup page using CakePhp.I have been added 2 to 3users information in the users table.Now i want to login with register user Email and password.How can i login with email instead of username using authentication?.I am using the cakephp version 2.4.2.Can u please help me?Thanks in advance.
Possible duplicate
Try configure it with:
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
);
See also Configuring Authentication handlers in the cookbook.
All Credits to: dhofstet
Auth is probably one of the most confusing parts of CakePHP when first introduced,
You need to change 'username'=>'username' to 'username'=>'email'
Below is a snippet out of one of my current projects, we use the email field instead of the username.
I would also suggest this video on CakePHP 2.0 Auth :
http://www.youtube.com/watch?v=zvwQGZ1BxdM
The Video Tutorials helped me a lot when beginning with CakePHP.
public $components = array(
'Auth' => array(
'loginAction' => array(
'controller' => 'user',
'action' => 'signin'
),
'loginRedirect' => '/',
'authError' => 'Did you really think you are allowed to see that?',
'userModel' => 'User',
'authenticate'=>array(
'Form'=>array(
'fields'=>array(
'username'=>'email',
'password'=>'password'
)
)
)
)
);