Breaking News
You are here : Home / Web development / CakePHP / Authorize Controller Actions Using Auth In CakePHP

Authorize Controller Actions Using Auth In CakePHP

Authorize Controller Actions Using Auth In CakePHP

Hello guys ! today we take a look at how we can authorize controller actions using auth component in cake  php. So we dont have to use ACL component for small level lets take a look at steps for authorize actions in cake php using auth:

here i m going to show you a small demonstration .we just need to have an extra field in users table called ‘role’. by tells the user role

here is the user table sql.lets firstly create a table.copy sql below and paste.

Now you need to create a user controller and the controller actions and corresponding views.I assume you might have known how to create those.
see firstly you should have auth component declared on your user can also create a appcontroller in root and add the components to it .so that all controllers inherit it.

Adding Auth:

now lets get to the point and say we want to authorize actions according to the role of the to achieve this we have to add a line to the user controller.

so this line tells the cake to look for isAuthorized method in user controller before performing any kind of action on users we add this method to Users controller as the code inside this function will be executed after user has been successfully logged in and tries to perform a action,when user do so the function is called and perform the checks and return true or false . see below the function:

Auth Logic To Authorize Controller Actions

As you seen every time user performs an action the isAuthorized is called .the above function checks if action is delete then check the role of the user and if user is admin then return true means grant yes other wise if user role is not admin then set a session message and return false means deny access.thatis how you authorize you controller action.
you can declare the code in the app_controller.php to make the scope application wide.every controller will inherit the code and the actions can be protected against the role of the can authorize as many actions you need to.
that was all ! thanks.comment if any kind of problem.

Thanks for visiting DesignAeon.


Tags : , ,

Leave a Reply

Want to join the discussion ? Feel Free to contribute !