Git Product home page Git Product logo

oauth2-php's Introduction

AuthBucket\OAuth2

Build Status Coverage Status Dependency Status Latest Stable Version Total Downloads License

The primary goal of AuthBucket\OAuth2 is to develop a standards compliant RFC6749 OAuth2.0 library; secondary goal would be develop corresponding wrapper Symfony2 Bundle and Drupal module.

This library bundle with a Silex based AuthBucketOAuth2ServiceProvider for unit test and demo purpose. Installation and usage can refer as below.

Installation

Simply add a dependency on authbucket/oauth2-php to your project's composer.json file if you use Composer to manage the dependencies of your project.

Here is a minimal example of a composer.json:

{
    "require": {
        "authbucket/oauth2-php": "~5.0"
    }
}

Parameters

The bundled AuthBucketOAuth2ServiceProvider come with following parameters:

  • authbucket_oauth2.model: (Optional) Override this with your own model classes, default with in-memory AccessToken for using resource firewall with remote debug endpoint.
  • authbucket_oauth2.model_manager.factory: (Optional) Override this with your backend model managers, e.g. Doctrine ORM EntityRepository, default with in-memory implementation for using resource firewall with remote debug endpoint.
  • authbucket_oauth2.user_provider: (Optional) For using grant_type = password, override this parameter with your own user provider, e.g. using InMemoryUserProvider or a Doctrine ORM EntityRepository that implements UserProviderInterface.

Services

The bundled AuthBucketOAuth2ServiceProvider come with following services controller which simplify the OAuth2.0 controller implementation overhead:

  • authbucket_oauth2.authorization_controller: Authorization Endpoint controller.
  • authbucket_oauth2.token_controller: Token Endpoint controller.
  • authbucket_oauth2.debug_controller: Debug Endpoint controller.

Registering

If you are using Silex, register AuthBucketOAuth2ServiceProvider as below:

$app->register(new AuthBucket\OAuth2\Silex\Provider\AuthBucketOAuth2ServiceProvider());

Moreover, enable following service providers if that's not already the case:

$app->register(new Silex\Provider\MonologServiceProvider());
$app->register(new Silex\Provider\SecurityServiceProvider());
$app->register(new Silex\Provider\ValidatorServiceProvider());

Usage

This library seperate the endpoint logic in frontend firewall and backend controller point of view, so you will need to setup both for functioning.

To enable the built-in controller with corresponding routing, you need to mount it manually:

$app->get('/api/oauth2/authorize', 'authbucket_oauth2.authorization_controller:indexAction')
    ->bind('api_oauth2_authorize');

$app->post('/api/oauth2/token', 'authbucket_oauth2.token_controller:indexAction')
    ->bind('api_oauth2_token');

$app->match('/api/oauth2/debug', 'authbucket_oauth2.debug_controller:indexAction')
    ->bind('api_oauth2_debug');

Below is a list of recipes that cover some common use cases.

Authorization Endpoint

We don't provide custom firewall for this endpoint, which you should protect it by yourself, authenticate and capture the user credential, e.g. by SecurityServiceProvider:

$app['security.default_encoder'] = function ($app) {
    return new Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder();
};

$app['security.user_provider.default'] = $app['security.user_provider.inmemory._proto']([
    'demousername1' => ['ROLE_USER', 'demopassword1'],
    'demousername2' => ['ROLE_USER', 'demopassword2'],
    'demousername3' => ['ROLE_USER', 'demopassword3'],
]);

$app['security.firewalls'] = [
    'api_oauth2_authorize' => [
        'pattern' => '^/api/oauth2/authorize$',
        'http' => true,
        'users' => $app['security.user_provider.default'],
    ],
];

Token Endpoint

Similar as authorization endpoint, we need to protect this endpoint with our custom firewall oauth2_token:

$app['security.firewalls'] = [
    'api_oauth2_token' => [
        'pattern' => '^/api/oauth2/token$',
        'oauth2_token' => true,
    ],
];

Debug Endpoint

We should protect this endpoint with our custom firewall oauth2_resource:

$app['security.firewalls'] = [
    'api_oauth2_debug' => [
        'pattern' => '^/api/oauth2/debug$',
        'oauth2_resource' => true,
    ],
];

Resource Endpoint

We don't provide other else resource endpoint controller implementation besides above debug endpoint. You should consider implement your own endpoint with custom logic, e.g. fetching user email address or profile image.

On the other hand, you can protect your resource server endpoint with our custom firewall oauth2_resource. Shorthand version (default assume resource server bundled with authorization server, query local model manager, without scope protection):

$app['security.firewalls'] = [
    'api_resource' => [
        'pattern' => '^/api/resource',
        'oauth2_resource' => true,
    ],
];

Longhand version (assume resource server bundled with authorization server, query local model manager, protect with scope demoscope1):

$app['security.firewalls'] = [
    'api_resource' => [
        'pattern' => '^/api/resource',
        'oauth2_resource' => [
            'resource_type' => 'model',
            'scope' => ['demoscope1'],
        ],
    ],
];

If authorization server is hosting somewhere else, you can protect your local resource endpoint by query remote authorization server debug endpoint:

$app['security.firewalls'] = [
    'api_resource' => [
        'pattern' => '^/api/resource',
        'oauth2_resource' => [
            'resource_type' => 'debug_endpoint',
            'scope' => ['demoscope1'],
            'options' => [
                'debug_endpoint' => 'http://example.com/api/oauth2/debug',
                'cache' => true,
            ],
        ],
    ],
];

Demo

The demo is based on Silex and AuthBucketOAuth2ServiceProvider. Read though Demo for more information.

You may also run the demo locally. Open a console and execute the following command to install the latest version in the oauth2-php directory:

$ composer create-project authbucket/oauth2-php authbucket/oauth2-php "~5.0"

Then use the PHP built-in web server to run the demo application:

$ cd authbucket/oauth2-php
$ ./bin/console server:run

If you get the error There are no commands defined in the "server" namespace., then you are probably using PHP 5.3. That's ok! But the built-in web server is only available for PHP 5.4.0 or higher. If you have an older version of PHP or if you prefer a traditional web server such as Apache or Nginx, read the Configuring a web server article.

Open your browser and access the http://127.0.0.1:8000 URL to see the Welcome page of demo application.

Also access http://127.0.0.1:8000/admin/refresh_database to initialize the bundled SQLite database with user account admin:secrete.

Documentation

OAuth2's documentation is built with Sami and publicly hosted on GitHub Pages.

To built the documents locally, execute the following command:

$ sami.php update .sami.php

Open build/sami/index.html with your browser for the documents.

Tests

This project is coverage with PHPUnit test cases; CI result can be found from Travis CI; code coverage report can be found from Coveralls.

To run the test suite locally, execute the following command:

$ phpunit -c phpunit.xml.dist

Open build/logs/html with your browser for the coverage report.

References

License

oauth2-php's People

Contributors

hswong3i avatar ponteineptique avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

oauth2-php's Issues

TODO: Resource Endpoint Firewall Should Check If Required Scope Provided

Now there is no way to define "which scope(s)" is required for "which path" in security.php. Once path protected by oauth2_resource, we just check if it is a valid access_token, now.

For the long run, it should update from:

'oauth2_resource' => array(
    'pattern' => '^/oauth2/resource$',
    'oauth2_resource' => true,
),

To something similar as:

'oauth2_resource' => array(
    'pattern' => '^/oauth2/resource$',
    'oauth2_resource' => array(
       'scope' => array('demoscope1', 'demoscope2', 'demoscope3'),
    ),
),

Interface 'Silex\ServiceProviderInterface' not found

Im using silex 2.* and authbucket. After register authbucket in web/index.php:
$app->register(new AuthBucket\OAuth2\Provider\AuthBucketOAuth2ServiceProvider());

im getting error :

Fatal error: Interface 'Silex\ServiceProviderInterface' not found in ..\vendor\authbucket\oauth2-php\src\Provider\AuthBucketOAuth2ServiceProvider.php on line 34

Add RESTful CRUD Controller for Client

Should add a new authorization server endpoint called /oauth2/client/* for client identity CURD management, e.g.

  • /oauth2/client: List all available client
  • /oauth2/client/add: Add a new client
  • /oauth2/client/{client_id}/edit: Edit client with id {client_id}
  • /oauth2/client/{client_id/}delete: Delete client with id {client_id}

TODO: Remote Resource Server Check Token with Authorization Server by Debug Endpoint

Assume resource server is independent with authorization server, refer to http://tools.ietf.org/html/rfc6749#section-7:

The methods used by the resource server to validate the access token (as well as any error responses) are beyond the scope of this specification but generally involve an interaction or coordination between the resource server and the authorization server.

Here we propose to utilize the authorization server debug endpoint:

  • Resource Server receive the RESTful request with an access_token from Client
  • Resource Server therefore prepare its own access_token with debug permission by client credentials grant between Authorization Server
  • Now Resource Server query debug endpoint with:
    • access_token: Resource Server's client credentials grant-ed token with debug permission
    • debug_token: the access_token provided by the Client
  • Debug endpoint return with raw information of provided access_token
  • Now Resource Server know the information about the access_token provided by Client, and so can start verify its permission accordingly

For the long run, it should update from:

'oauth2_debug' => array(
    'pattern' => '^/oauth2/debug$',
    'oauth2_debug' => true,
),

To something similar as:

// Authorization Server
'{token_endpoint} => array(
    'pattern' => '{token_path}',
    'oauth2_token' => true,
),
'{debug_endpoint}' => array(
    'pattern' => '{debug_path}',
    'oauth2_resource' => array(
        'resource_type' => 'model',
        'scope' => array('debug'),
    ),
),
// Resource Server
'{resource_endpoint}' => array(
    'pattern' => '{resource_path}',
    'oauth2_resource' => array(
        'resource_type' => 'debug_endpoint',
        'scope' => array('{scope}'),
        'options' => array(
            'token_path' => '{token_path}',
            'debug_path' => '{debug_path}',
            'client_id' => '{client_id}',
            'client_secret' => '{client_secret}',
        ),
    ),
),

TODO: Add Authorize Scope Confirmation Page

When accessing authorization endpoint, if resource owner not yet authorize corresponding scope, we should show a page for them to confirm that scope.

The workflow should be:

  • Access authorization endpoint
  • Firewall take action, check if coming with valid user token
    • If not yet authenticate, redirect to login form or using HTTP Basic
    • Once login, redirect back to original authorization endpoint
  • Pass firewall, with valid user token
  • Check the parameters from backend, including scope
    • If required scope not authorized yet, redirect to authorize scope confirmation page
    • Once scope authorized, saved into database, redirect back to original authorization endpoint
  • Generate code/token due to response_type

Should add a new authorization server endpoint called /oauth2/authorize/* for authorization CRUD management, e.g.

  • /oauth2/authorize: (RFC6749) Authorization endpoint
  • /oauth2/authorize/scope: (Create) Authorize scope confirmation page
  • /oauth2/{username}/authorize: (Read) List all authorized scope(s) for user {username}
  • /oauth2/{username}/authorize/{authorize_id}: (Read) List specific {authorize_id} detail for user {username}
  • /oauth2/{username}/authorize/{authorize_id}/edit: (Update) Update authorized scope(s) for user {username}
  • /oauth2/{username}/authorize/{authorize_id}/delete: (Delete) Remove authorized scope(s) for user {username}

Add configurable expire times for tokens

Right now Tokens have the following expire times:

This force any app to request tokens every hour, which is not the most desired behavior in many cases.

The idea is to be able to override these values through a configuration file and assume a default value in case said configuration file is not present or doesn't have the overrided key

Add RESTful CRUD Controller for Scope

Should add a new authorization server endpoint called /oauth2/scope/* for available scope CURD management, e.g.

  • /oauth2/scope: List all available scope
  • /oauth2/scope/add: Add a new scope
  • /oauth2/scope/{scope_id}/edit: Edit scope with id {scope_id}
  • /oauth2/scope/{scope_id/}delete: Delete scope with id {scope_id}

Client Secrets Not Compared in Constant Time

Documentation about using ORM Doctrine Implementation

Hi there,
First of all, really new to Silex & Symfony & Doctrine. That may explain why the following question could be stupid ;)
I am trying to use your oauth2-php in my own configuration where we have a simple Service for authentification with absolutely nothing else (Repo). My ROLE_ADMIN will manage the clients themselves, API Clients won't be created by anyone else than them. That was for context.

I don't reeally understand how to use your ORM implemantation of your own Class. It stands in the test, I have tried my best but I can't find a way to instantiate it. You can have a look at my code if you wish. I would be really grateful if you'd either explain to me what I am missing. I have tried copy your ORM stuff into my own folder and namespace (Perseids\Entity) but I get the message

#My command in my install folder
php ../vendor/bin/doctrine orm:schema-tool:create
#Results
PHP Fatal error:  Class 'Perseids\Entity\AbstractEntityRepository' not found in /home/thibault/dev/oauth/src/Entity/AuthorizeRepository.php on line 23

Just adding some stuff :
If I had the following lines to install/bootstrap.php :

    require_once "../src/Entity/AbstractEntityRepository.php";
    use Perseids\Entity\AbstractEntityRepository;

I get the following message :

#My command in my install folder
php ../vendor/bin/doctrine orm:schema-tool:create
#Results
No Metadata Classes to process.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.