Friday, November 11, 2016

How to implement Oauth 2.0 [bshaffer] in Laravel framework

Install the OAuth2 server and HTTP Foundation bridge dependencies using Composer:
  • composer require bshaffer/oauth2-server-php and
  • composer require bshaffer/oauth2-server-httpfoundation-bridge
Setup your database and run the provided migration Download migration from the link given below and add it in database.( https://github.com/julien-c/laravel-oauth2-server/commit/b290d4f699b9758696444e2d62dd82f0eeedcb7d) (php artisan db:migrate)

Seed your database using the provided script : Download test database contents from the link given below and add it in tables. (https://github.com/julien-c/laravel-oauth2-server/commit/8895c54cbf8ea8ba78aafab53a5a0409ce2f1ba2 ) (php artisan db:seed)

Setup your OAuth2 server: To be able to access the single instance anywhere in your Laravel app, you can attach it as a singleton:
  • Add the code give below in App Service Provider file. ( app->providers->AppServiceProvider.php ) or create a new service provider and add it.
public function register()
{
     App::singleton('oauth2', function()
     {
          $storage = new OAuth2\Storage\Pdo(array('dsn' => 'mysql:dbname=laravel_test;host=localhost', 'username' => 'root', 'password' => ''));
          $server = new OAuth2\Server($storage);

          $server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));
          $server->addGrantType(new OAuth2\GrantType\UserCredentials($storage));
          $server->addGrantType(new OAuth2\GrantType\RefreshToken($storage));

     return $server;
     });
}} 
To generate & regenerate token :
  • Add the code give below in routes file
Route::post('oauth/token', function()
{
    $bridgedRequest  = OAuth2\HttpFoundationBridge\Request::createFromRequest(Request::instance());
    $bridgedResponse = new OAuth2\HttpFoundationBridge\Response();
  
    $bridgedResponse = App::make('oauth2')->handleTokenRequest($bridgedRequest, $bridgedResponse);
  
    return $bridgedResponse;
});
Parameters used to generate token:

URL : http://localhost:8000/api/oauth/token

Headers Parameters:
  • Authorization → Basic dGVzdGNsaWVudDp0ZXN0cGFzcw== [ Basic base64_encode(client_id:client_password) ]
Body Parameters:
  • grant_type → password
  • username → user's name
  • password → user's password
Sample Result :
{
"access_token": "9cf3edc9f6d7437712a0f344872b04641eb336eb",
"expires_in": 3600,
"token_type": "Bearer",
"scope": null,
"refresh_token": "5d975d306fb0c28813caf2c79916890a2f4dbfe4"
}

Parameters used to re-generate token:

URL : http://localhost:8000/api/oauth/token

Headers Parameters:
  • Authorization → Basic dGVzdGNsaWVudDp0ZXN0cGFzcw== [ Basic base64_encode(client_id:client_password) ]
Body Parameters:
  • grant_type → refresh_token
  • refresh_token → refresh token stored in oauth_refresh_tokens table
Sample Result :
{
"access_token": "205edda287528d136d2ec0be32d8b5e1b572cc77",
"expires_in": 3600,
"token_type": "Bearer",
"scope": null
}

To authenticate token and to get token details (Authentication Server):
  • Add the code give below in routes file
Route::get('private', function()
{
 $bridgedRequest = OAuth2\HttpFoundationBridge\Request::createFromRequest(Request::instance());
 $bridgedResponse = new OAuth2\HttpFoundationBridge\Response();
  
 if (App::make('oauth2')->verifyResourceRequest($bridgedRequest, $bridgedResponse)) {
  
 $token = App::make('oauth2')->getAccessTokenData($bridgedRequest);
  
  return Response::json(array(
   'private' => 'stuff',
   'user_id' => $token['user_id'],
   'client' => $token['client_id'],
   'expires' => $token['expires'],
   ));
 }
 else
 {
  return Response::json(array(
   'error' => $bridgedResponse->getParameter('error'),
   'error_description' => $bridgedResponse->getParameter('error_description'),
   ), $bridgedResponse->getStatusCode());
 }
});

Parameters used to authenticate token:
 
URL :
http://localhost:8000/api/ private


Headers Parameters:
Authorization → Bearer 9b50c978cca15802000beaf13ef95c33e14f1a81 [Bearer Token]
{
"private": "stuff",
"user_id": "bshaffer",
"client": "testclient",
"expires": 1478822036
}

No comments:

Post a Comment