Frontend

Now that we have all the work done at the API level we need to adjust the frontend to store the access token once we log in to the app and pass the access token along with the request while accessing the API. We will also set up the expiration on the containers of the session because the token has expiration.

Modifying ApiClient.php

As this is the centralized point for all the API requests, this is the only place where we need to send the access token to the API. We need to first import the Container component by using the following code to access the sessions we are using to store the access token:

useZendSessionContainer;

After that, we will create a new property using the following code to store the session object to avoid creating it over and over again:

protected static $session = null;

Then we need to create the following method to retrieve the Container object:

public static function getSession()
{
    if (self::$session === null) {
        self::$session = new Container('oauth_session'),
    }
    
    return self::$session;
}

Now that we have this code in place to access the session, we need to modify the authenticate() method to pass the OAuth 2.0 data along with the request.

public static function authenticate($postData)
{
    $postData['grant_type'] = 'client_credentials';
    $postData['redirect_uri'] = 'http://example.com';
    $postData['client_id'] = 'zf2-client';
    $postData['client_secret'] = 'mysupersecretpass';

    $url = self::$endpointHost . self::$endpointUserLogin;
    return self::doRequest($url, $postData, Request::METHOD_POST);
}

As you can see, we have hardcoded the data in the method. We can move it to the configuration file for convenience, but for this example you will see it clearly here.

First, we need to specify the grant type. As we are working with client credentials, we should pass client_credentials on the grant_type variable. Then, we also need to send a client ID and a client secret. These two values will be similar to the consumer key and the consumer secret found in OAuth 1.0 and basically identifies each app that has access to OAuth 2.0 with a unique ID and a secret shared between the server and the app.

If you are going to develop a third-party access, you will need to generate these two values for each app you want to integrate and provide them to the developer of the app.

The last change we need to do is located in the doRequest() method and will take care of sending the access token to the API on each request. As the backend already ignores the access token for those URLs that don't have to be protected, we can always securely send it.

Before setting the parameters to the client, we need to add the following lines of code:

if ($postData === null) {
    $postData = array();
}

$postData['access_token'] = self::getSession()->accessToken;

As you can see, the preceding code adds the access token to the array used to set the parameters of the request.

Modifying Api.php

This is the last file we need to modify on the client in order to use OAuth 2.0. While authenticating a user, we must store the access token returned by the server. Let's see the code we need to add at the top of the authenticate() method:

if (array_key_exists('access_token', $result) &&
!empty($result['access_token'])) {
    $hydrator = new ClassMethods();
    $user = $hydrator->hydrate(
    ApiClient::getUser($this->username), new User()
    );

    $session = new Container('oauth_session'),
    $session->setExpirationSeconds($result['expires_in']);
    $session->accessToken = $result['access_token'];

    $response = new Result(
        Result::SUCCESS, 
        $user, 
        array('Authentication successful.')
    );
} else {
    $response = new Result(
        Result::FAILURE, NULL , array('Invalid credentials.')
    );
}

Right after calling the authenticate() method on the ApiClient object, we need to examine the response to see if it was successful and the API returned an access token; otherwise, we will return an error to the client. If the API returns an access token, we need to create a new container to store the data there and we will set up the expiration accordingly to the expiration sent by the API.

As you can see, we hydrate the user as before, but after that we create the container and we store the data inside.

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

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