PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 11, 2022

[FIXED] CakePHP 4, authenticating admin panel with Auth Plugin and scopes

 March 11, 2022     cakephp, php     No comments   

Issue

I have made a prefixed Admin section for my web application in CakePHP 4. In config/routes.php I scoped the Auth plugin as such (so only /admin/* would need login:

$routes->prefix('Admin', function (RouteBuilder $routes) {

$routes->registerMiddleware(
    'auth',
    new \Authentication\Middleware\AuthenticationMiddleware($this)
);
$routes->applyMiddleware('auth');
// etc. 

Because I wanted to have a simple landing page (e.g., localhost/admin) for the panel, I created an AdminController.php in the /Admin/ folder, and I've attempted to connect '/admin' to this controller so that the URL wont be a clunky localhost/admin/admin - but I'm getting an Auth error.

$routes->connect(
    '/admin',
    ['prefix' => 'Admin', 'controller' => 'Admin', 'action' => 'index']
 );

This produces the error: The request object does not contain the required authentication attribute

I tried to ameliorate this by attempting to scope the middleware again

$routes->scope('/admin', function(RouteBuilder $routes)
{
    $routes->registerMiddleware(
        'auth',
        new \Authentication\Middleware\AuthenticationMiddleware($this)
    );
    $routes->applyMiddleware('auth');
});

But this doesn't work, it gives the same error.


Solution

Don't create an extra route outside of the prefix, you can use / as the path to connect a route to the current prefix/scope path:

$routes->prefix('Admin', function (RouteBuilder $routes) {
    $routes->registerMiddleware(
        'auth',
        new \Authentication\Middleware\AuthenticationMiddleware($this)
    );
    $routes->applyMiddleware('auth');
    
    // this will connect `/admin`
    $routes->connect('/', ['controller' => 'Admin', 'action' => 'index']);

    // ...
}

See also

  • Cookbook > Routing > Prefix Routing
  • Cookbook > Routing > Quick Tour


Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing