Authentication

In this recipe will have the authentication model set up.

Getting ready

Repeat all steps from the Creating a REST server recipe in Getting ready and How to do it sections.

How to do it...

  1. Modify @app/controllers/FilmController to the following:
    <?php
    
        namespace appcontrollers;
    
        use appmodelsUser;
        use Yii;
        use yiihelpersArrayHelper;
        use yii
    estActiveController;
        use yiifiltersauthHttpBasicAuth;
    
        class FilmController extends ActiveController
        {
            public $modelClass = 'appmodelsFilm';
    
            public function behaviors()
            {
                return ArrayHelper::merge(parent::behaviors(),[
                    'authenticator' => [
                    'authMethods' => [
                        'basicAuth' => [
                            'class' =>HttpBasicAuth::className(),
                            'auth' => function ($username,$password) {
                                $user =User::findByUsername($username);
    
                                if ($user !== null && $user->validatePassword($password)){
                                    return $user;
                                }
    
                                return null;
                            },
                        ]
                    ]
                ]
    
            ]);
        }
    }

Open http://yii-book.app/films in a browser and make sure that we configure HTTP Basic Authentication:

How to do it...

Let's try to authenticate. Run this in the console:

curl -i -H "Accept:application/json" "http://yii-book.app/films"

And you will get the following:

HTTP/1.1 401 Unauthorized
Date: Thu, 24 Sep 2015 01:01:24 GMT
Server: Apache
X-Powered-By: PHP/5.5.23
Www-Authenticate: Basic realm="api"
Content-Length: 149
Content-Type: application/json; charset=UTF-8

{"name":"Unauthorized","message":"You are requesting with an invalid credential.","code":0,"status":401,"type":"yii\web\UnauthorizedHttpException"}
  1. And now try auth with cURL:
    curl -i -H "Accept:application/json" -u admin:admin "http://yii-book.app/films"
    
  2. You should then get a response that looks like this:
    HTTP/1.1 200 OK
    Date: Thu, 24 Sep 2015 01:01:40 GMT
    Server: Apache
    X-Powered-By: PHP/5.5.23
    Set-Cookie: PHPSESSID=8b3726040bf8850ebd07209090333103; path=/; HttpOnly
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Pragma: no-cache
    X-Pagination-Total-Count: 5
    X-Pagination-Page-Count: 1
    X-Pagination-Current-Page: 1
    X-Pagination-Per-Page: 20
    Link: <http://yii-book.app/films?page=1>; rel=self
    Content-Length: 301
    Content-Type: application/json; charset=UTF-8
    [{"id":1,"title":"Interstellar","release_year":2014},{"id":2,"title":"Harry Potter and the Philosopher's Stone","release_year":2001},{"id":3,"title":"Back to the Future","release_year":1985},{"id":4,"title":"Blade Runner","release_year":1982},{"id":5,"title":"Dallas Buyers Club","release_year":2013}]

How it works…

We've also added the authenticator behavior to the HttpBasicAuth class, so we will be able to authenticate with just a login and password. You might implement any authentication method that is described in the official guide in the RESTful web services section.

There's more…

There are different ways to send an access token:

  • HTTP Basic Auth
  • Query parameter
  • OAuth

Yii supports all of these authentication methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.59.231