Search code examples
cakephpauthenticationautologin

How to bypass the login screen in a CakePHP app (jSlate)?


I'm having problems integrating a CakePHP app (jSlate) into a bespoke non-Cake web application. All the alternative authentication scripts I've seen simply change the behaviour of the login form, in other words the login form still appears, and asks for username and password, but these are authenticated against an alternative source, such as LDAP.

What I actually want is for no login screen to appear at all. Instead I want a very simple behaviour:

  1. Detect if user is already logged in to third party app.
  2. If yes, automatically log them in to the CakePHP app (in this case jSlate).
  3. If no, redirect to the third party app login screen.

Is there a tutorial for a CakePHP authentication along these lines? Or does someone know how to do this? I've worked out how to do part 3, but this behaviour is kind of useless without parts 1 and 2...


Solution

  • You can put this into your AppController::beforeFilter:

    public function beforeFilter() {
        if (!$this->Auth->user()) {
            // if no user is currently logged in
    
            if ($this->Cookie->read(...)) {
            // or
            if ($_COOKIE[...]) {
            // or whatever else you want to detect
    
                $this->redirect('http://some.external/login/service');
            }
        }
    }
    

    This external login service would then presumably redirect the user back to your Cake app at some point with some sort of token. You just need to define a publicly accessible action (no auth required) which it can redirect back to. In that action, you check all the tokens you need and can then "manually" authenticate the user:

    $user = $this->User->find(/* find your Cake user by some id */);
    if ($user) {
        $this->Auth->login($user['User']['id']);
    }
    

    Congratulations, the user is now logged in as if he'd used a login form and has a valid Cake session.