Sainesh Mamgain
Sainesh Mamgain

Reputation: 785

Use Cakephp Auth component for webservices

I'm creating a web service for android app. I'm using cakephp 3 Auth. I am getting username and password from android app in $this->request->query['username'] and $this->request->query['password].

how can I use Auth component for identifying the user?

So far I've tried is:

public function login(){
    if(!empty($this->request->query['username']) && !empty($this->request->query['password'])){
        $this->loadComponent('Auth');
        $user=$this->Auth->identify($this->request->query['username'],$this->request->query['password']);
        if($user){
            $this->output(['status'=>'1','message'=>'Success','user_id'=>(string)$user->id,'plan_id'=>
                    (string)$user->plan_id]);
        }else{
            $this->output(['status'=>'0','message'=>'Invalid Username/Password.']);
        }
    }    
}

I am getting false when I'm using debug($user); even when I'm using correct credentials.

Upvotes: 2

Views: 260

Answers (1)

ndm
ndm

Reputation: 60463

You can't just throw stuff together and expect it to work... I mean, where do the docs say that AuthComponent::identify() would take username and password as arguments?

Also loading the auth component in an action is pretty pointless, as authentication would only work/be required for that single action. Again, don't just throw stuff together, read the docs, try to understand how things work, if necessary look at the source code, and then start coding as shown in the docs!

That being said, the default authenticator expects the credentials in the POST data

Form authentication

[...]

  • FormAuthenticate allows you to authenticate users based on form POST data. Usually this is a login form that users enter information into.

[...]

By default AuthComponent uses FormAuthenticate.

* emphasis mine

Cookbook > Controllers > Components > Authentication

So, ideally you would POST the credentials instead of passing them as query string parameters. If that isn't possible and you must use GET (you should have a good reason for that), then you could alternatively create a custom authenticator that fetches the data from the query, or even pass the query string data to the POST data before trying to authenticate the user,

$this->request->data['username'] = $this->request->query('username');
$this->request->data['password'] = $this->request->query('password');

that's somewhat ugly tough.

Loading the auth component

As already mentioned, you don't load the auth component in an action, as shown in the docs, this should be done in a controllers initialize() method, ideally, in case the complete application should be protected, this would be the AppController

public function initialize()
{
    parent::initialize();
    $this->loadComponent('Auth', /* ... */);
    // ...
}

Cookbook > Controllers > Components

See also

Upvotes: 2

Related Questions