How to grant client credential OAuth 2.0 in slim PHP

227 views Asked by At

I am new and was trying to study API using slim PHP, recently I was introduced to Postman and found out you can test API prior to code which was interesting, and then I got more deep into it and found Oauth 2.0, now the problem is in postman. I can get the bearer token easily and explore some API

postmen

but I can't find any resources showing me how can I implement this on my slim PHP file. by the way the project that I am testing is text. I didn't know about Postman before but this API doc introduced it and then I tried some tutorial on YouTube I got the authorization but that's in postman so how will I implement on slim-php?

I am clueless as I don't see any sample so I couldn't write any codes based on this. It looks like OAuth 2.0 is quite new.

1

There are 1 answers

0
odan On

OAuth 2.0 is a protocol that allows third-party applications to obtain limited access to an HTTP service. The Client Credentials grant is a simplified flow that's appropriate for machine-to-machine authentication where the client is the resource owner.

To implement the OAuth 2.0 Client Credentials Grant in Slim PHP, follow these steps:

Run:

composer require bshaffer/oauth2-server-php

Create the tables

Use the following schema to create the default database:

https://bshaffer.github.io/oauth2-server-php-docs/cookbook/

Run the following SQL to create an OAuth Client:

INSERT INTO oauth_clients (client_id, client_secret, redirect_uri) VALUES ("testclient", "testpass", "http://fake/");

Set up the OAuth 2.0 server

Configure the OAuth PDO connection:

use OAuth2\Storage\Pdo;
use OAuth2\Server;
use OAuth2\GrantType\ClientCredentials;
// ...

// Set up your database connection
$dsn = 'mysql:dbname=test;host=localhost';
$username = 'root';
$password = '';
$storage = new Pdo(['dsn' => $dsn, 'username' => $username, 'password' => $password]);

// Pass a storage object to the OAuth2 server class
$oauth = new Server($storage);

// Add the Client Credentials grant type (it is the simplest of the grant types)
$oauth->addGrantType(new ClientCredentials($storage));

Add endpoints:

The client will request an access token from this endpoint.

$app->post('/token', function (ServerRequestInterface $request, ResponseInterface $response) use ($oauth) {
    // Map PSR-7 request to OAuth2 Request
    $oAuthRequest = new OAuth2\Request(
        $request->getQueryParams(),
        (array)$request->getParsedBody(),
        [],
        $request->getCookieParams(),
        $request->getUploadedFiles(),
        $request->getServerParams()
    );

    // Map OAuth2 response to PSR-7 response
    $oauthResponse = $oauth->handleTokenRequest($oAuthRequest);
    $response = $response->withStatus($oauthResponse->getStatusCode());
    foreach ($oauthResponse->getHttpHeaders() as $header => $value) {
        $response = $response->withHeader($header, $value);
    }

    $params = $oauthResponse->getParameters();
    $response->getBody()->write(json_encode($params));

    return $response;
});

This is a protected resource that requires an access token for access.

$app->get('/resource', function (ServerRequestInterface $request, ResponseInterface $response) use ($oauth) {
    // Map PSR-7 request to OAuth2 Request
    // ...

    if (!$oauth->verifyResourceRequest($oAuthRequest)) {
        // Map OAuth2 response to PSR-7 response
        // ...

        return $response;
    }

    // The access token is valid, return the protected resource
    $response->getBody()->write(json_encode(['success' => true, 'message' => 'You accessed my APIs!']));
    return $response->withHeader('Content-Type', 'application/json');
});

Send a POST Request (using Postman) to generate a token:

POST http://localhost/token

{
  "grant_type": "client_credentials",
  "client_id": "testclient",
  "client_secret": "testpass"
}

The result:

{
  "access_token": "674f15fe84a6ee96420b7bd34df6bb5c16ee5103",
  "expires_in": 3600,
  "token_type": "Bearer",
  "scope": null
}

Send a GET request to the protected endpoint with the Authorization header:

GET http://localhost/resource

Authorization: Bearer 674f15fe84a6ee96420b7bd34df6bb5c16ee5103

Response:

{
  "success": true,
  "message": "You accessed my APIs!"
}