CakePHP 4 is a open source framework based on PHP language. It supports MVC pattern to work.
In CakePHP, authentication is the process of determining and verifying a user’s identity. It entails making sure the user is who they say they are and that they have the rights and privileges required to access the resources they have asked to access.
Components are a module of CakePHP 4 which shares it’s logic through out each controller. Inside this article we will see a commonly know component i.e AuthComponent of CakePHP 4 – How To Work with Authentication in CakePHP 4
Learn More –
- Complete Tutorial About CakePHP 4 basics Working Concept
- HTTP CURL Request Service in CodeIgniter 4 Tutorial
- HTTP Method Spoofing in CodeIgniter 4
- Image Manipulation Class in CodeIgniter 4 Tutorial
Let’s get started.
CakePHP 4 Installation
To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.
$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp
Above command will creates a project with the name called mycakephp.
What are Components of CakePHP 4?
Components are the functional section which is transparent to use. It shares it’s complete logic to each controller. Generally it’s a classes which we can use inside application via method
$this->loadComponent(<component_name>)
Components can be loaded either on individual controllers or using at Parent controller. I recommend to use to load component by parent Controller of application i.e AppController which is inside /src/Controller/AppController.php.
In AppController (parent controller) we have a constructor with the name of initialize() method. Have a look a code snippet as –
// Constructor of AppController public function initialize(): void { parent::initialize(); $this->loadComponent('RequestHandler'); $this->loadComponent('Flash'); }
There are few components which CakePHP 4 provides by default –
- RequestHandler
- Flash
- Auth
- Security
- Pagination
Also we can create own component in case if we need. There are very few simple steps to create, load and use it.
Inside this article, we will discuss about Auth Component of CakePHP 4.
Auth Component in CakePHP 4
For every web application, authentication is a common process. Nowadays every application supports security features. Identification for a valid user, checking for robots, authentication steps to verify a human normally a common process.
In CakePHP 4, Auth Component is also a default component provided to implement all authentication processes. It’s like a plugin which we can use by creating an instance of the class.
class AuthComponent(ComponentCollection $collection, array $config = [])
$this->Auth is an object which we can use for calling auth methods.
As, we have discussed to use any component in CakePHP we need to load it. Either we can load to parent controller or any of the controller. Inside this we will load it via Parent controller.
// AppController constructor public function initialize(): void { parent::initialize(); // load auth component $this->loadComponent("Auth"); }
CakePHP 4 Auth Component Configuration
We need to do some handlers settings of CakePHP 4 before using it. These are important settings. These settings plays their important roles while implementing Auth Component. First we should see the steps of handlers config –
- Authentication type – Inside Auth component in CakePHP 4, it support 3 authentication types. Types as Form, Basic, Digest. We will use here a Form type to authenticate. In Form auth, we need to create form fields. The key we will use for it as authenticate.
- Login Action – We need to provide about login action in detail. Login action means about controller that is used to login and it’s method. It is used to open login panel layout. Also if suppose we are using prefix for controller then we need to include as well. Key used for this handler – loginAction.
- Login Redirect – Login redirect handler called when a valid used logs in. Means from loginAction user will open a form, fill the details and submit. After successful authentication login redirect specified controller and it’s method will be used. Like we may say a dashboard page for user. Key used for this as loginRedirect.
- Logout Redirect – When user clicks on Logout button of dashboard panel, then for logout this logout redirect handler will get called and work. Where user should go after logout we configure inside this key. The defined key we use for it as – logoutRedirect.
Let’s a complete configuration of above handlers into AuthComponent of CakePHP 4.
// AppController constructor public function initialize(): void { parent::initialize(); // load auth component $this->loadComponent("Auth", [ "authenticate" => [ "Form" => [ // using form type authenticate "fields" => [ // form fields used to login "username" => "email", "password" => "password" ], "userModel" => "Users" // Model used to validate user ] ], "loginAction" => [ // /users/login - route "controller" => "Users", // controller "action" => "login" // method ], "loginRedirect" => [ // /users/dashboard "controller" => "Dashboards", "action" => "index" ], "logoutRedirect" => [ // /users/login "controller" => "Users", "action" => "login" ] ]); }
Suppose when we have developed application controllers inside a extra Admin directory like – /src/Controller/Admin. It means we need to include in namespace of controllers and also on auth configuration. Because the controller we will use inside handlers is inside Admin folder.
// /admin/users/login
"loginAction" => [
"controller" => "Users",
"action" => "login",
"prefix" => "Admin"
]
Her, we have taken a single handler to see how can we use prefix key. Same we need to do for all.
Routes, Views & Controller of Auth Component
Routes config for application is an important redirection method. Every application has a routes configuration file to manage redirects. In CakePHP 4 we have /config/routes.php file.
As, we are using some routes for Auth handlers from above configurations. So, we need to set these routes into routes.php file.
$route->connect("/users/login", ["controller" => "Users", "action" => "login"]); $route->connect("/users/dashboard", ["controller" => "Dashboards", "action" => "index"]); $route->connect("/users/logout", ["controller" => "Users", "action" => "logout"]);
In loginAction, logoutRedirect we are using Users Controller & action (method) is login. login is a method inside Users Controller.
In this methods, we are handling 2 two request types – GET & POST.
GET Request type – To open login page with form fields.
POST Request type – To Submit form data to validate user details.
Let’s see the code of login method –
// login() of Users Controller public function login() { // checking if user already logged in or not. // if logged in the $user_id will have id value of user else // empty value $user_id = $this->Auth->user("id"); if (!empty($user_id)) { return $this->redirect("/admin"); } else { // login page if ($this->request->is("post")) { // checking request type // validate the user from users table $userdata = $this->Auth->identify(); // default method of auth component if ($userdata) { // settings user data $this->Auth->setUser($userdata); return $this->redirect($this->Auth->redirectUrl()); } else { $this->Flash->error("Invalid login details"); } } } $this->set("title", "Site Title | Log In"); }
Above code is given to open user login form and handling form submission as well.
Let’s understand about available methods of AuthComponent.
User Identification Methods – AuthComponent CakePHP 4
To understand this topic very clearly, go back to the login(). We can see inside that, we have some methods used. As we discussed previously about $this->Auth instance which is of AuthComponent class.
By the help of $this->Auth instance will call some predefined methods which handles behind the screen about Authentication in application.
Methods are –
- $this->Auth->identify() – This method is used to verify the login details of user. When we fill user details to form and submit, loginAction handler works. To check user existence at database, this method automatically takes care to match user details. If user exists then it returns the user data object with all details.
- $this->Auth->user(“id”) – This method returns user ID value after login. If it returns null or empty value it means their is no user logged in system.
- $this->Auth->setUser($userdata) – setUser method sets user data to CakePHP session. The variable we have inside this method $userdata is coming from method identify().
- $this->Auth->redirectUrl() – redirectUrl() returns the loginRedirect handler url. If you go to this loginRedirect handler, you should see a controller & method is associated with the call. So this method simply returns the URL of the user dahsboard.
Successfully, we have seen about the method of AuthComponent i.e $this->Auth.
Read Session Values of AuthComponent CakePHP 4
Reading users data from session is very very simple. Open your AppController which is parent controller of application. Also when you dump data $this->Auth, you will get all idea about data settings.
In that controller we need to define a life cycle method as –
function beforeRender(\Cake\Event\EventInterface $event) { // store user data to Auth variable. // we will use this Auth variable to get user data $this->set("Auth", $this->Auth->user()); }
We have defined the Auth variable which have user data. Now, we need to call user values to view layout files.
Suppose, $this->Auth->user() returns user object which contains “name”, “email” keys. To access the value of name from that, we will use the syntax like – $Auth[‘name’]. Auth is the variable which we have define inside beforeRender().
Any template file in CakePHP 4, simplu use it – <?php echo $Auth[‘name’] ?> OR <?= $Auth[‘name’] ?>
Alternative, suppose we have used as $this->set(“Auth”, $this->Auth); In that case in template files we need to use <?= $Auth->user(‘name’) ?>
Allow Routes – Auth Settings to Controller
In some cases we want to run some routes without login. What I mean, suppose we have used Users Controller in Auth Handlers as did previously. If we do so, then all the methods of UsersController are protected. They need a valid user to access, because they are now authenticated URLs.
In that case we need to allow some routes in which we don’t need any login. So for that we have to use allow() method of $this->Auth.
public function beforeFilter(\Cake\Event\EventInterface $event) { // methods name we can pass here which we want to allow without login parent::beforeFilter($event); $this->Auth->allow(["site"]); }
User Logout – Auth Component – CakePHP 4
Logout functionality is that functional part of any portal where we destroy or flush user session values.
In CakePHP 4, AuthComponent provides a method to do this. $this->Auth->logout(). This will destroy user session values and return logoutRedirect URL from auth component handler.
Let’s see the code of logout() of UserController –
// It will flush user session values and return logoutRedirect URL public function logout() { return $this->redirect($this->Auth->logout()); }
We hope this article helped you to learn about How To Work with Authentication in CakePHP 4 Tutorial in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.
I like this site very much so much superb info.
I like this web site because so much useful stuff on here
:D.
Saved as a favorite, I love your blog!
It?s nearly impossible to find knowledgeable people in this particular subject, but
you sound like you know what you?re talking about!
Thanks
I am really pleased to read this blog posts which carries lots of
helpful information, thanks for providing these
statistics.
I believe you have noted some very interesting points,
thank you for the post.
You really make it seem so easy with your presentation but I find this topic to be really something that
I think I would never understand. It seems too complicated and extremely broad for
me. I am looking forward for your next post, I’ll try to
get the hang of it!
Your way of describing the whole thing in this post is really nice,
all be able to without difficulty know it, Thanks
a lot.
Greetings I am so delighted I found your website, I really found you by accident, while I was browsing
on Digg for something else, Anyways I am here now and would just like to say many thanks
for a tremendous post and a all round thrilling blog (I also love
the theme/design), I don’t have time to read through it all at the moment but I have book-marked
it and also added in your RSS feeds, so when I have time
I will be back to read much more, Please do keep up the superb job.
Hello, just wanted to tell you, I enjoyed this article.
It was funny. Keep on posting!
I was very happy to discover this website.
I want to to thank you for ones time just for this fantastic read!!
I definitely enjoyed every part of it and I have you saved to fav to
see new stuff in your blog.
Outstanding post, you have pointed out some fantastic points, I
besides believe this is a very good website.
That is a great tip particularly to those fresh to the blogosphere.
Brief but very precise info… Thank you for sharing this one.
A must read post!
Thanks for sharing your thoughts on website. Regards
I think this is among the most significant
info for me. And i’m glad reading your article.
But should remark on few general things, The web site style is wonderful, the articles
is really nice : D. Good job, cheers
Nice blog here! Also your web site loads up fast! What web host are you using?
Can I get your affiliate link to your host? I wish my website
loaded up as fast as yours lol
Great beat ! I wish to apprentice whilst you amend
your site, how can i subscribe for a weblog web
site? The account aided me a applicable deal. I were tiny
bit familiar of this your broadcast offered vibrant clear concept.
I’ve been exploring for a little bit for any high quality
articles or blog posts in this sort of house . Exploring in Yahoo I at last stumbled upon this web site.
Studying this information So i am glad to express that I
have a very just right uncanny feeling I discovered exactly what
I needed. I most definitely will make sure to do not put out of your mind this website
and provides it a look regularly.
you are really a excellent webmaster. The web site loading pace is incredible.
It sort of feels that you are doing any distinctive trick.
Moreover, The contents are masterpiece. you have performed a great
job in this matter!
I truly value your piece of work, Great post.
Wow! In the end I got a weblog from where I know how to genuinely obtain useful data concerning my study and knowledge.
Very good info. Lucky me I discovered your
site by accident (stumbleupon). I have book marked it for later!
Hi there, just became alert to your blog through Google, and found that it’s truly informative.
I am gonna watch out for brussels. I will appreciate if you continue this in future.
Lots of people will be benefited from your writing. Cheers!
Normally I do not read post on blogs, however I would like
to say that this write-up very pressured
me to check out and do so! Your writing taste has been surprised me.
Thank you, quite nice article.
Hurrah! Finally I got a blog from where I can in fact take valuable
information concerning my study and knowledge.
Everything is very open with a really clear description of the issues.
It was truly informative. Your website is useful. Many thanks for sharing!
I wanted to thank you for this good read!!
I certainly enjoyed every little bit of it. I have got you saved
as a favorite to look at new things you post…
Hey there I am so glad I found your website, I really found you by mistake, while I
was looking on Digg for something else, Regardless I
am here now and would just like to say thanks for a marvelous post and a
all round entertaining blog (I also love the theme/design),
I don’t have time to read it all at the minute but I have saved it and also added in your RSS feeds, so when I
have time I will be back to read more, Please do keep up the excellent job.
Thanks