GithubHelp home page GithubHelp logo

zf-oauth2-doctrine's Introduction

OAuth2 Doctrine ORM Adapter for Apigility

Build Status Documentation Status Gitter Patreon Total Downloads

This provides a Doctrine adapter for zfcampus/zf-mvc-auth and zfcampus/zf-oauth2 and entity definitions for all aspects of OAuth2 including Authorization Code, Access Tokens, Refresh Tokens, JWT & JTI, and Scopes.

Versions

  • 1.x series is for PHP 5.5 to 7.0.
  • 2.x series is for PHP 7.1 onward.
  • 3.x series is for PHP 7.1 onward and uses bigint instead of integer, scope fixture, and bcrypt cost of 10.

Entity Relationship Diagram Entity Relationship Diagram created with Skipper

zf-oauth2-doctrine's People

Contributors

basz avatar dannyvdsluijs avatar hagmann avatar juizmill avatar sergiohermes avatar thomasvargiu avatar tomhanderson avatar viniciusgava 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

zf-oauth2-doctrine's Issues

Conflict between zf-oauth2-doctrine and doctrine-module

Hello,

When I activate zf-oauth2-doctrine, I can't use anymore the console command of doctrine-module package (ie. "doctrine-module migrations:diff --no-interaction")

The problem is :
PHP Notice: Undefined index: zf-oauth2-doctrine in /var/www/vendor/api-skeletons/zf-oauth2-doctrine/Module.php on line 49
and then :
PHP Catchable fatal error: Argument 1 passed to Zend\Config\Config::__construct() must be of the type array, null given, called in /var/www/vendor/api-skeletons/zf-oauth2-doctrine/Module.php on line 49 and defined in /var/www/vendor/zendframework/zend-config/src/Config.php on line 57

Can you help me to solve this or find a workaround ?

Support zfcampus/zf-mvc-auth 1.3+

Modify this module to work as storage for from a service. This will allow multiple OAuth2 installations per Apigility installation allowing for multiple installations per API.

[Mapping] FAIL - The entity-class

to perform

bin/doctrine-module orm:validate-schema

is returning this error:

* The field HitCursos\V1\Entity\User#client is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity ZF\OAuth2\Doctrine\Entity\Client#user does not contain the required 'inversedBy="client"' attribute.
* The field HitCursos\V1\Entity\User#accessToken is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity ZF\OAuth2\Doctrine\Entity\AccessToken#user does not contain the required 'inversedBy="accessToken"' attribute.
* The field HitCursos\V1\Entity\User#authorizationCode is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity ZF\OAuth2\Doctrine\Entity\AuthorizationCode#user does not contain the required 'inversedBy="authorizationCode"' attribute.
* The field HitCursos\V1\Entity\User#refreshToken is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity ZF\OAuth2\Doctrine\Entity\RefreshToken#user does not contain the required 'inversedBy="refreshToken"' attribute.

Any suggestion?

Adapter not recognized by Apigility

Hi there,

I managed to view response from where it comes (see attached images)
1
2

Notice: Undefined index: adapter
Notice: Undefined index: dsn

I believe it is related to this piece of code:

'zf-mvc-auth' => array(
        'authentication' => array(
            'adapters' => array(
                'oauth2_doctrine' => array(
                    'adapter' => 'ZF\\MvcAuth\\Authentication\\OAuth2Adapter',
                    // 'adapter' => 'oauth2.doctrineadapter.default',
                    'storage' => array(
                        'storage' => 'oauth2.doctrineadapter.default',
                        'route' => '/oauth',
                        //'dsn' => '',
                        /*'adapter' => 'pdo',
                        'dsn' => 'mysql:host=localhost;dbname=apigility',
                        'username' => 'root',
                        'password' => '123',*/
                    ),      
                ),
            ),
        ),
    ),

Maybe something about 'adapter' => 'ZF\MvcAuth\Authentication\OAuth2Adapter', ??

Do you have any idea what I'm missing or doing wrong?

Getting "Forbidden" when using Authorization Bearer

Hi

I'm getting 403 Forbidden when i use the Authorization header Bearer. I can POST to the oauth endpoint with a username and password, and it creates and returns an accessToken(i checked db, it's there) but when i use that accessToken with Bearer, i get 403 forbidden.
I used PDO adapter before this module, and that worked, so not sure if i'm missing a config or something like that.

Any ideas on what i could be missing?

Default Entities private properties

I'd like to extend the default entities in my application. All the entity attributes are private rather than protected which prevents me from using an extended version of the entity classes.

My use case is that I need the tables to store uuid's rather than integer id's and to achieve this I need to generate the uuid within the entity constructor. e.g.:

namespace ZF\ApigilityDoctrine\Entity;

use Ramsey\Uuid\Uuid;
use ZF\OAuth2\Doctrine\Entity\AccessToken as ZFOAuth2_AccessToken;

class AccessToken extends ZFOAuth2_AccessToken
{

    public function __construct()
    {
        $this->id = Uuid::uuid4();
        parent::__construct();
    }
}

This fails as the entity attributes are not accessible due to being private. Is there a reason that they couldn't be made protected instead?

HTTP Basic Auth is Broken Because of AuthenticationPostListener

If there is an http basic adapter and try to use it with an API service (given that there is an api service using oauth2_doctrine auth adapter):

Catchable fatal error: Argument 1 passed to ZF\OAuth2\Doctrine\Identity\AuthenticationPostListener::findAccessToken() must be of the type array, string given, called in /Users/hani/Projects/MedcorTM-PHP-API/vendor/api-skeletons/zf-oauth2-doctrine-identity/src/AuthenticationPostListener.php on line 33 and defined in /Users/hani/Projects/MedcorTM-PHP-API/vendor/api-skeletons/zf-oauth2-doctrine-identity/src/AuthenticationPostListener.php on line 44

Query Builder error on auth_identity_fields

Hi,
have 'auth_identity_fields' => array('email') in my config file and this throw an 500 QueryException error saying: �[Syntax Error] line 0, col 77: Error: Expected =, <, <=, <>, >, >=, !=, got ':username'.
Using only username does not throw an error. Using only email does throw an error as well as using both fields.

Can not change field datatype

Tried to change field datatype in AccessToken entity and noticed that configuration for datatype is ignored.

Also how can I add additional indexes to table, is that possible?

grant_type Error

php public/index.php

result

ZF\OAuth2\Doctrine\Console

index.php oauth2:client:create Create client
index.php oauth2:client:list List clients
index.php oauth2:client:update --id=# Update client
index.php oauth2:client:delete --id=# Delete client
index.php oauth2:scope:create Create scope
index.php oauth2:scope:list List scopes
index.php oauth2:scope:update --id=# Update scope
index.php oauth2:scope:delete --id=# Delete scope
index.php oauth2:public-key:create --id=# Create public key. id is a client record.
index.php oauth2:public-key:delete --id=# Delete public key. id is a client record.
index.php oauth2:jwt:create --id=# Create a JWT entry. id is a client record.
index.php oauth2:jwt:list List JWT entries
index.php oauth2:jwt:delete --id=# Delete a JWT entry. id is a jwt record. `

when I run

php public/index.php oauth2:client:create in terminal I get nothing

Problem command orm:schema-tool:update

When you run the command orm:schema-tool:update as mapping generates this error:

  [Doctrine\Common\Persistence\Mapping\MappingException]  
  Class 'ZF\OAuth2\Entity\AccessToken' does not exist 

Not possible to use a custom naming strategy (No column X on table Client_OAuth2)

I'm attempting to validate/drop/create my schema. With this module and a config like within: "apigility-oauth2-doctrine-skeleton" I'm getting the following error:

[Doctrine\DBAL\Schema\SchemaException]                             
  There is no column with name 'clientId' on table 'Client_OAuth2'. 

Can't quite work out what's causing it as the XML definitions look fine.

Add logging to user authentications

Hello, and thanks again for continuing to maintain this nice module!

I'm looking at adding in logging about authentication events. Do you have a suggested way to hook into this functionality?

Example scenarios:

  1. user logs in for the first time (get access token / refresh token for the first time)
  2. user requests a refresh of their access token.
  3. User fails to authenticate (e.g., be able to add in detection of DDOS or brute-force attempts).

It seems like hooking into the existing apigility authentication events aren't quite the right approach because those would fire on every request -- unless I'm misunderstanding something.

For both I plan on pushing in a simple syslog which would then be handled outside of the scope of the application.

syslog(LOG_INFO, 'user_auth event. userId: ' . $user->getId());

Additional data may be captured as well such as source IP and so forth; however, the above is just a contrived example.

Thanks in advance :-)

how to use with Zf-Oauth2

i try to use with zf oauth2 in mysql and entities with doctrine annotation
but dont work
schema

CREATE TABLE oauth_clients (
client_id VARCHAR(80) NOT NULL,
client_secret VARCHAR(80) NOT NULL,
redirect_uri VARCHAR(2000) NOT NULL,
grant_types VARCHAR(80),
scope VARCHAR(2000),
user_id VARCHAR(255),
CONSTRAINT clients_client_id_pk PRIMARY KEY (client_id)
);
CREATE TABLE oauth_access_tokens (
access_token VARCHAR(40) NOT NULL,
client_id VARCHAR(80) NOT NULL,
user_id VARCHAR(255),
expires TIMESTAMP NOT NULL,
scope VARCHAR(2000),
CONSTRAINT access_token_pk PRIMARY KEY (access_token)
);
CREATE TABLE oauth_authorization_codes (
authorization_code VARCHAR(40) NOT NULL,
client_id VARCHAR(80) NOT NULL,
user_id VARCHAR(255),
redirect_uri VARCHAR(2000),
expires TIMESTAMP NOT NULL,
scope VARCHAR(2000),
id_token VARCHAR(2000),
CONSTRAINT auth_code_pk PRIMARY KEY (authorization_code)
);
CREATE TABLE oauth_refresh_tokens (
refresh_token VARCHAR(40) NOT NULL,
client_id VARCHAR(80) NOT NULL,
user_id VARCHAR(255),
expires TIMESTAMP NOT NULL,
scope VARCHAR(2000),
CONSTRAINT refresh_token_pk PRIMARY KEY (refresh_token)
);
CREATE TABLE oauth_users (
username VARCHAR(255) NOT NULL,
password VARCHAR(2000),
first_name VARCHAR(255),
last_name VARCHAR(255),
CONSTRAINT username_pk PRIMARY KEY (username)
);
CREATE TABLE oauth_scopes (
type VARCHAR(255) NOT NULL DEFAULT "supported",
scope VARCHAR(2000),
client_id VARCHAR (80),
is_default SMALLINT DEFAULT NULL
);
CREATE TABLE oauth_jwt (
client_id VARCHAR(80) NOT NULL,
subject VARCHAR(80),
public_key VARCHAR(2000),
CONSTRAINT jwt_client_id_pk PRIMARY KEY (client_id)
);

Error 500 /aouth request bearer grant password

if i update my composer , the request return status 500 internal error

Unable to istanziate Service Manager

I started from a clean project

there is my composer log:

Loading composer repositories with package information
Updating dependencies (including require-dev)

  • Removing zendframework/zendxml (1.0.0)
  • Installing zendframework/zendxml (1.0.2)
    Loading from cache
  • Removing zendframework/zend-stdlib (2.5.1)
  • Installing zendframework/zend-stdlib (2.7.6)
    Loading from cache
  • Installing zendframework/zend-hydrator (1.1.0)
    Loading from cache
  • Removing zendframework/zend-eventmanager (2.5.1)
  • Installing zendframework/zend-eventmanager (2.6.3)
    Loading from cache
  • Removing zendframework/zend-code (2.5.1)
  • Installing zendframework/zend-code (2.6.2)
    Loading from cache
  • Removing zendframework/zend-server (2.5.1)
  • Installing zendframework/zend-server (2.6.1)
    Loading from cache
  • Removing zendframework/zend-math (2.5.1)
  • Installing zendframework/zend-math (2.6.0)
    Loading from cache
  • Installing container-interop/container-interop (1.1.0)
    Loading from cache
  • Removing zendframework/zend-validator (2.5.1)
  • Installing zendframework/zend-validator (2.6.0)
    Loading from cache
  • Removing zendframework/zend-uri (2.5.1)
  • Installing zendframework/zend-uri (2.5.2)
    Loading from cache
  • Removing zendframework/zend-http (2.5.1)
  • Installing zendframework/zend-http (2.5.4)
    Loading from cache
  • Removing zendframework/zend-view (2.5.1)
  • Installing zendframework/zend-view (2.6.4)
    Loading from cache
  • Removing zendframework/zend-json (2.5.1)
  • Installing zendframework/zend-json (2.6.1)
    Loading from cache
  • Removing zendframework/zend-servicemanager (2.5.1)
  • Installing zendframework/zend-servicemanager (2.7.5)
    Loading from cache
  • Removing zendframework/zend-text (2.5.1)
  • Installing zendframework/zend-text (2.6.0)
    Loading from cache
  • Removing zendframework/zend-filter (2.5.1)
  • Installing zendframework/zend-filter (2.6.1)
    Loading from cache
  • Removing zendframework/zend-inputfilter (2.5.1)
  • Installing zendframework/zend-inputfilter (2.6.0)
    Loading from cache
  • Removing zendframework/zend-form (2.5.1)
  • Installing zendframework/zend-form (2.7.0)
    Loading from cache
  • Installing psr/http-message (1.0)
    Loading from cache
  • Installing zendframework/zend-diactoros (1.3.3)
    Loading from cache
  • Installing zendframework/zend-psr7bridge (0.2.1)
    Loading from cache
  • Removing zendframework/zend-mvc (2.5.1)
  • Installing zendframework/zend-mvc (2.7.1)
    Loading from cache
  • Removing zendframework/zend-dom (2.5.1)
  • Installing zendframework/zend-dom (2.6.0)
    Loading from cache
  • Removing zendframework/zend-console (2.5.1)
  • Installing zendframework/zend-console (2.6.0)
    Loading from cache
  • Removing symfony/yaml (v2.7.0)
  • Installing symfony/yaml (v3.0.3)
    Loading from cache
  • Removing sebastian/version (1.0.5)
  • Installing sebastian/version (1.0.6)
    Loading from cache
  • Removing sebastian/global-state (1.0.0)
  • Installing sebastian/global-state (1.1.1)
    Loading from cache
  • Removing sebastian/recursion-context (1.0.0)
  • Installing sebastian/recursion-context (1.0.2)
    Loading from cache
  • Removing sebastian/exporter (1.2.0)
  • Installing sebastian/exporter (1.2.1)
    Loading from cache
  • Removing sebastian/environment (1.2.2)
  • Installing sebastian/environment (1.3.5)
    Loading from cache
  • Removing sebastian/diff (1.3.0)
  • Installing sebastian/diff (1.4.1)
    Loading from cache
  • Removing sebastian/comparator (1.1.1)
  • Installing sebastian/comparator (1.2.0)
    Loading from cache
  • Removing phpunit/php-text-template (1.2.0)
  • Installing phpunit/php-text-template (1.2.1)
    Loading from cache
  • Removing doctrine/instantiator (1.0.4)
  • Installing doctrine/instantiator (1.0.5)
    Loading from cache
  • Removing phpunit/php-timer (1.0.5)
  • Installing phpunit/php-timer (1.0.7)
    Loading from cache
  • Removing phpunit/php-file-iterator (1.4.0)
  • Installing phpunit/php-file-iterator (1.4.1)
    Loading from cache
  • Removing phpunit/php-token-stream (1.4.1)
  • Installing phpunit/php-token-stream (1.4.8)
    Loading from cache
  • Removing phpspec/prophecy (v1.4.1)
  • Installing phpspec/prophecy (v1.6.0)
    Loading from cache
  • Removing phpunit/phpunit-mock-objects (2.3.3)
  • Installing phpunit/phpunit-mock-objects (3.0.6)
    Loading from cache
  • Installing sebastian/code-unit-reverse-lookup (1.0.0)
    Loading from cache
  • Removing phpunit/php-code-coverage (2.1.5)
  • Installing phpunit/php-code-coverage (3.2.1)
    Loading from cache
  • Installing myclabs/deep-copy (1.5.0)
    Loading from cache
  • Installing sebastian/resource-operations (1.0.0)
    Loading from cache
  • Removing phpunit/phpunit (4.7.2)
  • Installing phpunit/phpunit (5.2.9)
    Loading from cache
  • Removing zendframework/zend-test (2.5.1)
  • Installing zendframework/zend-test (2.6.1)
    Loading from cache
  • Removing zendframework/zend-tag (2.5.1)
  • Installing zendframework/zend-tag (2.6.1)
    Loading from cache
  • Removing zendframework/zend-session (2.5.1)
  • Installing zendframework/zend-session (2.6.2)
    Loading from cache
  • Removing zendframework/zend-serializer (2.5.1)
  • Installing zendframework/zend-serializer (2.6.1)
    Loading from cache
  • Removing zendframework/zend-progressbar (2.5.1)
  • Installing zendframework/zend-progressbar (2.5.2)
    Loading from cache
  • Removing zendframework/zend-permissions-acl (2.5.1)
  • Installing zendframework/zend-permissions-acl (2.6.0)
    Loading from cache
  • Removing zendframework/zend-paginator (2.5.1)
  • Installing zendframework/zend-paginator (2.6.0)
    Loading from cache
  • Removing zendframework/zend-navigation (2.5.1)
  • Installing zendframework/zend-navigation (2.6.0)
    Loading from cache
  • Removing zendframework/zend-modulemanager (2.5.1)
  • Installing zendframework/zend-modulemanager (2.7.1)
    Loading from cache
  • Removing zendframework/zend-crypt (2.5.1)
  • Installing zendframework/zend-crypt (2.6.0)
    Loading from cache
  • Removing zendframework/zend-mail (2.5.1)
  • Installing zendframework/zend-mail (2.6.1)
    Loading from cache
  • Installing psr/log (1.0.0)
    Loading from cache
  • Removing zendframework/zend-log (2.5.1)
  • Installing zendframework/zend-log (2.7.1)
    Loading from cache
  • Removing zendframework/zend-i18n-resources (2.5.1)
  • Installing zendframework/zend-i18n-resources (2.5.2)
    Loading from cache
  • Removing zendframework/zend-i18n (2.5.1)
  • Installing zendframework/zend-i18n (2.6.0)
    Loading from cache
  • Removing zendframework/zend-file (2.5.1)
  • Installing zendframework/zend-file (2.6.1)
    Loading from cache
  • Removing zendframework/zend-feed (2.5.1)
  • Installing zendframework/zend-feed (2.7.0)
    Loading from cache
  • Removing zendframework/zend-di (2.5.1)
  • Installing zendframework/zend-di (2.6.0)
    Loading from cache
  • Removing zendframework/zend-db (2.5.1)
  • Installing zendframework/zend-db (2.7.0)
    Loading from cache
  • Removing zendframework/zend-config (2.5.1)
  • Installing zendframework/zend-config (2.6.0)
    Loading from cache
  • Removing zendframework/zend-captcha (2.5.1)
  • Installing zendframework/zend-captcha (2.5.4)
    Loading from cache
  • Removing zendframework/zend-cache (2.5.1)
  • Installing zendframework/zend-cache (2.6.1)
    Loading from cache
  • Removing zendframework/zend-barcode (2.5.1)
  • Installing zendframework/zend-barcode (2.6.0)
    Loading from cache
  • Removing zendframework/zend-authentication (2.5.1)
  • Installing zendframework/zend-authentication (2.5.3)
    Loading from cache
  • Removing zendframework/zendframework (2.5.1)
  • Installing zendframework/zendframework (2.5.3)
    Loading from cache
  • Removing zfcampus/zf-hal (1.2.1)
  • Installing zfcampus/zf-hal (1.3.0)
    Loading from cache
  • Removing zfcampus/zf-apigility-admin (1.3.3)
  • Installing zfcampus/zf-apigility-admin (1.4.1)
    Loading from cache

Writing lock file
Generating autoload files

DoctrineModule 0.10.0 support

Is there a problem with updating dependency of the doctrine/doctrine-module to 0.10.0? Dependency for the doctrine/doctrine-module is set to ^0.9 currently.

Module (ZF\Oauth2\Doctrine) could not be initialized.

Hi,

I'm not able to load this module. Can you give some advice what to look at to get this running? I went through the documentation and did the following changes:

  • I copied config/oauth2.doctrine-orm.global.php.dist and changed the entity to use Application\Entity\User
  • I added the zf-mvc-auth config into zf-mvc-auth-oauth2-override.global.php it gets returned in an array
  • I added 'storage' => 'oauth2.doctrineadapter.default', in my oauth2.global.php
  • doctrine is setup to be connected to a database and without ZF\Oauth2\Doctrine loaded I'm able to get orm:info and can create the structure.

Once ZF\Oauth2\Doctrine is enabled the app simply doesn't start with the message: Module (ZF\Oauth2\Doctrine) could not be initialized.
I was not able to follow the error until the depth where the real error happens. Can you tell me where I can look at or where to check what's wrong to get this module running?

Cheers
Andi

Deprecated warning on Mapper\MapperManager

Deprecated: ServiceLocatorAwareInterface is deprecated and will be removed in version 3.0, along with the ServiceLocatorAwareInitializer. Please update your ZF\OAuth2\Doctrine\Mapper\MapperManager plugin manager factory to inject the parent service locator via the constructor. in /var/www/vendor/zendframework/zend-mvc/src/Service/ServiceManagerConfig.php on line 175

Call Stack
#   Time    Memory  Function    Location
1   0.0006  241200  {main}( )   .../index.php:0
2   0.0192  730768  Zend\Mvc\Application::init( )   .../index.php:51
3   0.4235  6836936 Zend\Mvc\Application->bootstrap( )  .../Application.php:281
4   0.4883  7557544 Zend\EventManager\EventManager->triggerEvent( ) .../Application.php:169
5   0.4883  7557576 Zend\EventManager\EventManager->triggerListeners( ) .../EventManager.php:251
6   0.6999  9777736 call_user_func:{/var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php:490} ( )   .../EventManager.php:490
7   0.6999  9777848 ZF\OAuth2\Doctrine\Module->onBootstrap( )   .../EventManager.php:490
8   0.6999  9778024 Zend\ServiceManager\ServiceManager->get( )  .../Module.php:39
9   0.6999  9778808 Zend\ServiceManager\ServiceManager->create( )   .../ServiceManager.php:532
10  0.6999  9778808 Zend\ServiceManager\ServiceManager->doCreate( ) .../ServiceManager.php:599
11  0.6999  9778856 Zend\ServiceManager\ServiceManager->createFromFactory( )    .../ServiceManager.php:636
12  0.6999  9778856 Zend\ServiceManager\ServiceManager->createServiceViaCallback( ) .../ServiceManager.php:1096
13  0.6999  9779232 call_user_func:{/var/www/vendor/zendframework/zend-servicemanager/src/ServiceManager.php:936} ( )   .../ServiceManager.php:936
14  0.6999  9779360 ZF\OAuth2\Doctrine\Module->ZF\OAuth2\Doctrine\{closure}( )  .../ServiceManager.php:936
15  0.7051  9900064 ZF\OAuth2\Doctrine\Adapter\DoctrineAdapterFactory->createService( ) .../Module.php:52
16  1.0777  14661904    ZF\OAuth2\Doctrine\Adapter\DoctrineAdapterFactory->loadMapperManager( ) .../DoctrineAdapterFactory.php:36
17  1.0777  14661952    Zend\ServiceManager\ServiceManager->get( )  .../DoctrineAdapterFactory.php:71
18  1.0777  14662904    Zend\ServiceManager\ServiceManager->create( )   .../ServiceManager.php:532
19  1.0777  14662904    Zend\ServiceManager\ServiceManager->doCreate( ) .../ServiceManager.php:599
20  1.0800  14703784    call_user_func:{/var/www/vendor/zendframework/zend-servicemanager/src/ServiceManager.php:666} ( )   .../ServiceManager.php:666
21  1.0800  14703816    Zend\Mvc\Service\ServiceManagerConfig->Zend\Mvc\Service\{closure}( )    .../ServiceManager.php:666
22  1.0800  14704488    trigger_error ( )   .../ServiceManagerConfig.php:175

zf-oauth2-doctrine wokrs very slowly

Hello, standart zf-oauth2 working for 0.3 seconds from start request to receive response
But when I am try to use zf-oauth2-doctrine it works 3.5 seconds.
It very slowly for me
What me do?

Integrity constraint violation

Whilst deleting a client a constant error is thrown if tokens exists, not sure if this is correct/intended behavior

An exception occurred while executing 'DELETE FROM oauth2_client WHERE clientId = 'plhw-client'':

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (plhw_data.oauth2_refreshtoken, CONSTRAINT FK_5B5D887919EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_client (id))

same is true for oauth2_accesstoken...

adding 'on-delete="CASCADE"' on the join Column definitions fixes it

documentation request surrounding module configuration

First of all thanks for writing this module. I'm looking forward to using this!

It seems like there's a missing step once the module is configured and entities are built out. How does one then use zf-oauth2-doctrine as the oauth authentication server?

If I don't have anything configured in local.php (auto-generated by apigility if I were to specify a PDO oauth adapter) then I get this exception when attempting to authenticate against /oauth:

An exception was raised while creating "ZF\OAuth2\Controller\Auth"; no instance returned

Is there some additional configuration tidbits that need to be added to enable the oauth authentication URI, and appropriate handlers?

Thanks!

Get to user entity from password authentication

On my application, I'm trying to perform a login and retrieve the user profile back from the services.

I'm authenticating the user by performing an /oauth POST call with the following body:

{
    "grant_type": "password",
    "username": "test",
    "password": "test",
    "client_id": "webappLocal"
}

And getting this back from the apigility server:

{
  "access_token": "0105d6385de255969d00b3a69af47687e9b8dff9",
  "expires_in": 3600,
  "token_type": "Bearer",
  "scope": "",
  "refresh_token": "666f1ecc0e7f4e52dcd2c3daa5273684ad6c24c6"
}

I have a /user endpoint where I could get the user information for a giver user_id, but I'm missing such Id. At this point, I'm only aware of the access_token, username and password of the user.

What's the best way to solve this? Can I modify the authentication response to include a user_id? Should I perform a user search by username (maybe /user?username=test)? I'd appreciate some direction...

Error in RuntimeReflectionService.php

when doing a ./vendor/bin/doctrine-module orm:schema-tool:update --force I get following error:
In RuntimeReflectionService.php line 80:
Property BMEntities\Entity\User::$client does not exist

What is the cause of this error?

Question Re :

I am currently working on adding zf-auth-doctrine to my application (Map based Facilities Mgt).

We have built all of our models using Sparxsystem's Enterprise Architect. I was not able to import OAuth2-orm.module.xml into EA, so I have built the database model based on the file and the publish ER Diagram
in OAuth2-orm.module.xml, I saw the following, which seems to contradict the ER Diagrman

<many-to-many mn-entity="\ZF\OAuth2\Doctrine\Entity\AccessTokenToScope" uuid="d6c88e38-48c1-43d7-b5e9-b6902ee48e7c">
      <many-to-many-entity name="\ZF\OAuth2\Doctrine\Entity\Scope" owning-side="true" alias="scope" uuid="391c57b9-1832-4a9a-b7fb-75b2c5c59ebf">
        <many-to-many-field from="scope_id" to="id"/>
      </many-to-many-entity>
     
 <many-to-many-entity name="\ZF\OAuth2\Doctrine\Entity\AccessToken" owning-side="false" alias="accessToken" uuid="1a2f2f70-ba2a-49c8-a50c-ffe2206b4013">
        <many-to-many-field from="access_token_id" to="id"/>
</many-to-many-entity>

But the Diagram indicates this is a many-to-one (one-to-many).
I have built my model on the ER Diagram as it seems more correct.
Am I missing something here?

I should point out that to my mind it seems that all the 1:n relationships are incorrectly coded in the xml.

If anyone is interested in the EA model I built I can provide it.

Adding Module

Should it be mentioned at installation or is this to obvious?

Module needs actually be loaded: application.config.php

return array(
    'modules' => array(
       /* ...  */
       'ZF\OAuth2\Doctrine',
       /* ...  */
   )
)

Column definitions according to OAuth specifications

According to bshaffer his OAuth cookbook there are specific column definitions for valid OAuth database storage:

CREATE TABLE oauth_clients (client_id VARCHAR(80) NOT NULL, client_secret VARCHAR(80), redirect_uri VARCHAR(2000) NOT NULL, grant_types VARCHAR(80), scope VARCHAR(100), user_id VARCHAR(80), CONSTRAINT clients_client_id_pk PRIMARY KEY (client_id));
CREATE TABLE oauth_access_tokens (access_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT access_token_pk PRIMARY KEY (access_token));
CREATE TABLE oauth_authorization_codes (authorization_code VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), redirect_uri VARCHAR(2000), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT auth_code_pk PRIMARY KEY (authorization_code));
CREATE TABLE oauth_refresh_tokens (refresh_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(255), expires TIMESTAMP NOT NULL, scope VARCHAR(2000), CONSTRAINT refresh_token_pk PRIMARY KEY (refresh_token));
CREATE TABLE oauth_users (username VARCHAR(255) NOT NULL, password VARCHAR(2000), first_name VARCHAR(255), last_name VARCHAR(255), CONSTRAINT username_pk PRIMARY KEY (username));
CREATE TABLE oauth_scopes (scope TEXT, is_default BOOLEAN);
CREATE TABLE oauth_jwt (client_id VARCHAR(80) NOT NULL, subject VARCHAR(80), public_key VARCHAR(2000), CONSTRAINT jwt_client_id_pk PRIMARY KEY (client_id));

In our custom entities we added these column specifics in the entity class definitions like this:

@ORM\Column(type="string", name="client_id", length=80, nullable=false)
@ORM\Column(type="string", name="client_secret", length=80, nullable=true)
@ORM\Column(type="string", name="redirect_uri", length=2000, nullable=false)
etc etc.

I would like to use the default entities that come with the library for our application, but I cannot because these column declarations are missing.
This is needed because without these specific column definitions the columns created in the database (when automatically creating database tables from the entity definitions) will not correspond to the OAuth specs.

I can make a pull request where I add column definitions according to OAuth specs to these columns.

Problem with orm:schema-tool:create

Hello
Excuse my english

I have a problem executing the command

orm: schema-tool: create

the error is as follows
image

when making a

image

I was reviewing the documentation but everything is fine
I do not know if you have any suggestions ...

apigility 1.1 compatibility issue?

'An alias by the name "zfoauth2provideruserid" or "ZF\OAuth2\Provider\UserId" already exists'.

The issue is that the zf-oauth2-doctrine module redeclares this invokable and it is now in conflict with Apigility 1.1:

// zfcampus/zf-oauth2/config/module.config.php
'service_manager' => array(
'aliases' => array(
'ZF\OAuth2\Provider\UserId' => 'ZF\OAuth2\Provider\UserId\Request',
),
'invokables' => array(
'ZF\OAuth2\Provider\UserId\Request' => 'ZF\OAuth2\Provider\UserId\Request',
),
compare with
// zfcampus/zf-oauth2-doctrine/config/modulle.config.php

'service_manager' => array(
'invokables' => array(
'ZF\OAuth2\Provider\UserId' =>
'ZF\OAuth2\Provider\UserId\AuthenticationService',
),

Note that the key is the same for both. Re-declaring the same key is causing a fatal exception to be thrown.

configurable table names

Hi, I'm not sure if you are willing to persui this but in IMO think I configurable tables names is a feature people would want. As a personal preference I tend to keep all table names (and column names) in lower case and functional grouped (prefixing 'oauth2' instead of appending)

Doing a little research I learned that to do this one should write an EventListener and since one is already present in this project it not hard to add this.

table names of the main entities are easy. Those of the join tables are a little harder (need to think up a good config name). But I've got a prototype running here.

So, my question. Would you consider accepting a PR for this? If not - no problem - i'll write my own EventListener.

table constraints for non 'id' PK on user table

In combination with ZfcUser and ZfcUserDoctrine I'm getting incorrect CONSTRAINTS

note the REFERENCES user (id) vs REFERENCES user (user_id)

php public/index.php orm:schema-tool:create --dump-sql | grep user
CREATE TABLE user (user_id INT AUTO_INCREMENT NOT NULL, username VARCHAR(255) DEFAULT NULL, email VARCHAR(255) DEFAULT NULL, display_name VARCHAR(50) DEFAULT NULL, password VARCHAR(128) NOT NULL, state SMALLINT DEFAULT NULL, createdAt DATETIME NOT NULL, updatedAt DATETIME NOT NULL, UNIQUE INDEX UNIQ_8D93D649F85E0677 (username), UNIQUE INDEX UNIQ_8D93D649E7927C74 (email), PRIMARY KEY(user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE AccessToken_OAuth2 (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, accessToken VARCHAR(255) DEFAULT NULL, expires DATETIME DEFAULT NULL, INDEX IDX_C092BBF419EB6921 (client_id), INDEX IDX_C092BBF4A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE AuthorizationCode_OAuth2 (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, authorizationCode VARCHAR(255) DEFAULT NULL, redirectUri LONGTEXT DEFAULT NULL, expires DATETIME DEFAULT NULL, idToken LONGTEXT DEFAULT NULL, INDEX IDX_7DED2FDD19EB6921 (client_id), INDEX IDX_7DED2FDDA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE Client_OAuth2 (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, clientId VARCHAR(255) DEFAULT NULL, secret VARCHAR(255) DEFAULT NULL, redirectUri LONGTEXT DEFAULT NULL, grantType LONGTEXT DEFAULT NULL COMMENT '(DC2Type:array)', INDEX IDX_A66D48A8A76ED395 (user_id), UNIQUE INDEX idx_clientId_unique (clientId), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE RefreshToken_OAuth2 (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, refreshToken VARCHAR(255) DEFAULT NULL, expires DATETIME DEFAULT NULL, INDEX IDX_EEBE59C919EB6921 (client_id), INDEX IDX_EEBE59C9A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
// constraints
ALTER TABLE AccessToken_OAuth2 ADD CONSTRAINT FK_C092BBF4A76ED395 FOREIGN KEY (user_id) REFERENCES user (id);
ALTER TABLE AuthorizationCode_OAuth2 ADD CONSTRAINT FK_7DED2FDDA76ED395 FOREIGN KEY (user_id) REFERENCES user (id);
ALTER TABLE Client_OAuth2 ADD CONSTRAINT FK_A66D48A8A76ED395 FOREIGN KEY (user_id) REFERENCES user (id);
ALTER TABLE RefreshToken_OAuth2 ADD CONSTRAINT FK_EEBE59C9A76ED395 FOREIGN KEY (user_id) REFERENCES user (id);

instead of

// ...
ALTER TABLE AccessToken_OAuth2 ADD CONSTRAINT FK_C092BBF4A76ED395 FOREIGN KEY (user_id) REFERENCES user (user_id);
ALTER TABLE AuthorizationCode_OAuth2 ADD CONSTRAINT FK_7DED2FDDA76ED395 FOREIGN KEY (user_id) REFERENCES user (user_id);
ALTER TABLE Client_OAuth2 ADD CONSTRAINT FK_A66D48A8A76ED395 FOREIGN KEY (user_id) REFERENCES user (user_id);
ALTER TABLE RefreshToken_OAuth2 ADD CONSTRAINT FK_EEBE59C9A76ED395 FOREIGN KEY (user_id) REFERENCES user (user_id);

Configuration of name of configuration

I have been trying to implement zf-oauth2-doctrine and zf-oauth2-doctrine-mutatetablenames
but when it's came to use it I found out that "zf-oauth2-doctrine-mutatetablenames" module expects 'zf-oauth2-doctrine' config will have "storage_settings" key with exactly same data as in your docs in "default" section. So, when I change "default" to required, your module shows me error that the key "default" doesn't exists. Of course, I can have both keys, bu it's not a good way to solve this problem. Could you tell me what am I doing wrong?

use_jwt_access_tokens option

I've implemented authorization using Doctrine and it works fine if the
'use_jwt_access_tokens' option is set to false.

When I enable 'use_jwt_access_tokens' => true during authentication I get access_tokens and refresh_tokens as JTW, but during authorization they don't work. If the JWT token is not the same as access_token, how do I get it working?

I thought the workflow would be the same, but instead the shorter random string I'll get detailed, encrypted JWT.

Here is a detailed question:
https://stackoverflow.com/questions/48917174/how-to-access-protected-resource-in-apigility-using-jwt

In another issue #29 regarding JWT you mentioned this article:
http://tomhanderson.blogspot.com/2015/05/jwt-in-oauth2-with-apigility-and.html
but it's not accessible anymore.

Mapping issues - Similar to #6

For some reason getting the mapping to a user entity is not working for me. Any help would be much appreciated as this looks to be the last step before I can fully utilize this module!

I've tried a number of things:

  1. removing the dynamic mapping and specifying the @manytoone relationships doesn't work because that then complains that the other side doesn't have the @onetomany's configured.
  2. using only dynamic mappings and removing all 'mapping' => array() configuration params
  3. no mappings and using the test as a base entity.
  4. Ideally, getting a real ORM entity mapped then having the dynamic stuff appended (this case), which I believe would be the normal case for 99% of other users who have a real user entity.

Thanks in advance :-)

I have a basic User entity as follows:

<?php
namespace DICommon\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 *
 * @author Jack
 *        
 */
class User implements \ZF\OAuth2\Doctrine\Entity\UserInterface
{

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $password;

    /**
     * @ORM\Column(type="array")
     */
    protected $roles;

    // BEGIN dynamically handled by zf-oauth2-doctrine module
    protected $email;

    protected $accessToken;

    protected $authorizationCode;

    protected $client;

    protected $refreshToken;

    // END dynamically handled by zf-oauth2-doctrine module
    public function __construct()
    {
        $this->roles = new ArrayCollection();
    }

    /*
     * (non-PHPdoc)
     * @see \ZF\OAuth2\Doctrine\Entity\UserInterface::getAccessToken()
     */
    public function getAccessToken()
    {
        return $this->accessToken;
    }

    /*
     * (non-PHPdoc)
     * @see \ZF\OAuth2\Doctrine\Entity\UserInterface::getAuthorizationCode()
     */
    public function getAuthorizationCode()
    {
        return $this->authorizationCode;
    }

    /*
     * (non-PHPdoc)
     * @see \ZF\OAuth2\Doctrine\Entity\UserInterface::getClient()
     */
    public function getClient()
    {
        return $this->client;
    }

    /*
     * (non-PHPdoc)
     * @see \ZF\OAuth2\Doctrine\Entity\UserInterface::getRefreshToken()
     */
    public function getRefreshToken()
    {
        return $this->refreshToken;
    }

    public function getRoles()
    {
        return $this->roles;
    }

    public function getArrayCopy()
    {
        return array(
            'id' => $this->getId(),
            'username' => $this->getUsername(),
            'password' => $this->getPassword(),
            'profile' => $this->getProfile(),
            'email' => $this->getEmail(),
            'roles' => $this->getRoles()
        );
    }
}

The oauth2.doctrine-orm.global.php configuration is the same as referenced in the .dist file for Doctrine ORM. except the $userEntity variable has been replaced by the DICommon\Entity\User string.

The output of php public/index.php orm:validate-schema is as follows:

$ php public/index.php orm:validate-schema
[Mapping]  FAIL - The entity-class 'DICommon\Entity\User' mapping is invalid:

* The field DICommon\Entity\User#client is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity ZF\OAuth2\Doctrine\Entity\Client#user does not contain the required 'inversedBy="client"' attribute.

* The field DICommon\Entity\User#accessToken is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity ZF\OAuth2\Doctrine\Entity\AccessToken#user does not contain the required 'inversedBy="accessToken"' attribute.

* The field DICommon\Entity\User#authorizationCode is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity ZF\OAuth2\Doctrine\Entity\AuthorizationCode#user does not contain the required 'inversedBy="authorizationCode"' attribute.

* The field DICommon\Entity\User#refreshToken is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity ZF\OAuth2\Doctrine\Entity\RefreshToken#user does not contain the required 'inversedBy="refreshToken"' attribute.

[Database] FAIL - The database schema is not in sync with the current mapping file.

jwt tokens

I tried to work with jwt tokens (unsuccessfully still) one thing i noticed the tokens are much longer then 40 chars. columns should be text to be able to query them by token

if you agree I'l update the orm config and PR

Implicit flow implementation with authentication views

Hello,
I'd like to integrate the implicit flow as part of my application's authentication strategy. That being said after chatting on IRC #apigility it appears that the authentication step is not yet implemented where a user object is stored in local session storage (or even as a doctrine session-object) to support the implicit grant strategy properly.

Steps to reproduce:

  • in configuration (global.php)
 'zf-oauth2' => array(
        'storage' => 'ZF\OAuth2\Doctrine\Adapter\DoctrineAdapter',
        'allow_implicit' => true,
    )
  • navigate to /oauth/authorize?client_id={SOME_CLIENT_ID}&response_type=token&state=abc
  • click on Yes to authorize the client id.

Due to the lack of a complete authentication strategy for implicit grant I believe the following exception is generated:

File:
E:\Bitbucket\example\com.example.api\vendor\zfcampus\zf-oauth2-doctrine\src\Mapper\AbstractMapper.php:217

Message:
Relation was not found: user_id:

Stack trace:
#0 E:\Bitbucket\example\com.example.api\vendor\zfcampus\zf-oauth2-doctrine\src\Adapter\DoctrineAdapter.php(540): ZF\OAuth2\Doctrine\Mapper\AbstractMapper->exchangeOAuth2Array(Array)
#1 E:\Bitbucket\example\com.example.api\vendor\bshaffer\oauth2-server-php\src\OAuth2\ResponseType\AccessToken.php(84): ZF\OAuth2\Doctrine\Adapter\DoctrineAdapter->setAccessToken('7f12517e9ef734e...', 'com.example...', NULL, 1430422400, '')
#2 E:\Bitbucket\example\com.example.api\vendor\bshaffer\oauth2-server-php\src\OAuth2\ResponseType\AccessToken.php(55): OAuth2\ResponseType\AccessToken->createAccessToken('com.example...', NULL, '', false)
#3 E:\Bitbucket\example\com.example.api\vendor\bshaffer\oauth2-server-php\src\OAuth2\Controller\AuthorizeController.php(90): OAuth2\ResponseType\AccessToken->getAuthorizeResponse(Array, NULL)
#4 E:\Bitbucket\example\com.example.api\vendor\bshaffer\oauth2-server-php\src\OAuth2\Server.php(303): OAuth2\Controller\AuthorizeController->handleAuthorizeRequest(Object(OAuth2\Request), Object(OAuth2\Response), true, NULL)
#5 E:\Bitbucket\example\com.example.api\vendor\zfcampus\zf-oauth2\src\Controller\AuthController.php(169): OAuth2\Server->handleAuthorizeRequest(Object(OAuth2\Request), Object(OAuth2\Response), true, NULL)
#6 E:\Bitbucket\example\com.example.api\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractActionController.php(82): ZF\OAuth2\Controller\AuthController->authorizeAction()
#7 [internal function]: Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#8 E:\Bitbucket\example\com.example.api\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(444): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#9 E:\Bitbucket\example\com.example.api\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(205): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#10 E:\Bitbucket\example\com.example.api\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractController.php(118): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#11 E:\Bitbucket\example\com.example.api\vendor\zendframework\zendframework\library\Zend\Mvc\DispatchListener.php(93): Zend\Mvc\Controller\AbstractController->dispatch(Object(ZF\ContentNegotiation\Request), Object(Zend\Http\PhpEnvironment\Response))
#12 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#13 E:\Bitbucket\example\com.example.api\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(444): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#14 E:\Bitbucket\example\com.example.api\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(205): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#15 E:\Bitbucket\example\com.example.api\vendor\zendframework\zendframework\library\Zend\Mvc\Application.php(314): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#16 E:\Bitbucket\example\com.example.api\public\index.php(63): Zend\Mvc\Application->run()
#17 {main}

I would like to propose that an authentication strategy is implemented with a basic login screen (userid, password, remember me for N days) [where N >= some configuration param] as well as a logout screen in this module to keep things cohesive.

My question to you is: Do you think that this feature request belongs in this module?

Thanks!

Transition to laminas-api-tools

Hi,
are there plans to transition this into Laminas Project? Since you already moved DoctrineModule it would be great to move this too.
It would also be great to see the following Repos to migrate too

zf-oauth2-doctrine-permissions-acl
zf-doctrine-hydrator
zf-doctrine-audit

Configuration problem

Hello, First of all, thank you for this module, I was seeking a project like this.
I am beginner in apigility I am trying to configure a project to work with apigility, doctrine and oauth.
I add the project to composer, copy the configuration(oauth2.doctrine-orm.global.php) to autoload and change it to my user entity. I add too the modules too.
When I browser to localhost:8888/oauth I receive this message:

The storage configuration for OAuth2 is missing

I don't know what is wrong.

local.php

return array(
    'zf-mvc-auth' => array(
        'authentication' => array(
            'adapters' => array(
                'zf-oauth2-doctrine' => array(
                    'adapter' => 'ZF\\OAuth2\\Doctrine\\Adapter\\DoctrineAdapter',
                ),
            ),
        ),
    ),
);

global.php

$userEntity = 'Rick\Common\Entity\User';

return array(
    'zf-oauth2-doctrine' => array(
        'storage' => 'ZF\OAuth2\Doctrine\Adapter\DoctrineAdapter',
        'storage_settings' => array(
            'object_manager' => 'doctrine.entitymanager.orm_default',
            'event_manager' => 'doctrine.eventmanager.orm_default',
            'driver' => 'doctrine.driver.orm_default',
            'enable_default_entities' => true,
            'bcrypt_cost' => 14, # match zfcuser
            'auth_identity_fields' => array('email','document'),
            // Dynamically map the user_entity to the client_entity
            'dynamic_mapping' => array(
                'user_entity' => array(
                    'entity' => $userEntity,
                    'field' => 'user',
                ),
.
.
.

application.config.php

return array(
    'modules' => array(
        'Rick\\Site',
        'Rick\\Common',
        'ZendDeveloperTools',
        'DoctrineModule',
        'DoctrineORMModule',
        'ZF\\Apigility',
        'ZF\\Apigility\\Provider',
        'AssetManager',
        'ZF\\ApiProblem',
        'ZF\\MvcAuth',
        'ZF\\OAuth2',
        'ZF\\Hal',
        'ZF\\ContentNegotiation',
        'ZF\\ContentValidation',
        'ZF\\Rest',
        'ZF\\Rpc',
        'ZF\\Versioning',
        'ZF\\DevelopmentMode',
        'Phpro\\DoctrineHydrationModule',
        'ZF\\Apigility\\Doctrine\\Server',
        'ZF\\OAuth2\\Doctrine',
        'ZF\\OAuth2\\Doctrine\\MutateTableNames',
        'RickClientApi',
    ),

Thank you!

How to add scopes to a client

version: "zfcampus/zf-oauth2-doctrine": "^0.3.4",
I am using forms to add a new client which has a selection of grant types and scopes. In my form I have added scopes using an ObjectSelect as so:

    $this->add(
        [
            'type' => 'DoctrineModule\Form\Element\ObjectSelect',
            'name' => 'scope',
            'options' => [
                'object_manager' => $this->objectManager,
                'target_class'   => 'ZF\OAuth2\Doctrine\Entity\Scope',
                'property'       => 'scope',
                'label' => 'Scope',
                'instructions' => ''
            ],
            'attributes' => [
                'required' => 'required',
                'multiple' => true,
                'class' => 'form-control input-medium select2me',
            ]
        ]
    );

The form renders as expected however once submitted I get the following error on:

$this->clientForm->isValid()

Catchable fatal error: Argument 1 passed to ZF\OAuth2\Doctrine\Entity\Client::addScope() must be an instance of ZF\OAuth2\Doctrine\Entity\Scope, instance of Doctrine\Common\Collections\ArrayCollection given, called in /var/www/cloud/vendor/doctrine/doctrine-module/src/DoctrineModule/Stdlib/Hydrator/Strategy/AllowRemoveByValue.php on line 71 and defined in /var/www/cloud/vendor/zfcampus/zf-oauth2-doctrine/src/Entity/Client.php on line 466

This error makes sense since the client scope methods are as so:

public function addScope(Scope $scope)
{
$this->scope[] = $scope;
return $this;
}

public function removeScope(Scope $scope)
{
$this->scope->removeElement($scope);
}

And the posted form is offering an array:

'client' =>
array (size=7)
'id' => string '4' (length=1)
'clientId' => string 'test_client' (length=11)
'grantType' =>
array (size=2)
0 => string 'implicit' (length=8)
1 => string 'urn:ietf:params:oauth:grant-type:jwt-bearer' (length=43)
'scope' =>
array (size=2)
0 => string '1' (length=1)
1 => string '2' (length=1)

I am not quite sure what I need to change in order to get this to work.

I was thinking of changing the field name to something like myScopes and then once I have persisted the client to add the scopes one at a time. The other alternative was to load each scopeObject and add the client to it.

These seem like a hack to me and I am probably doing something that I should not be doing...

Any advice most welcome!

client_id is not identifier column and has no unique constraint

In the entity model for this module the client_id is not an identifier column, instead a separate identifier column is used in the mapper for Client here

Would it not be better to simply use the client_id as an identifier column?
Since the client_id is not an INDEX should there not be an unique constraint added for client_id?

EDIT
My bad, I noticed that unique constraint is added here, but the first question remains...

DynamicMappingSubscriber: Argument #2 is not an array and error to get $clientIdField

Hello, I got some errors in the DynamicMappingSubscriber.

Errors because argument two is not a array:

\ZF\OAuth2\Doctrine\EventListener\DynamicMappingSubscriber:143
from this

$this->getConfig()->refresh_token_entity->additional_mapping_data

to this

$this->getConfig()->refresh_token_entity->additional_mapping_data->toArray()

\ZF\OAuth2\Doctrine\EventListener\DynamicMappingSubscriber:128
from this

$this->getConfig()->authorization_code_entity->additional_mapping_data

to this

$this->getConfig()->authorization_code_entity->additional_mapping_data->toArray()

\ZF\OAuth2\Doctrine\EventListener\DynamicMappingSubscriber:98
from this

$this->getConfig()->client_entity->additional_mapping_data

to this

$this->getConfig()->client_entity->additional_mapping_data->toArray()

I got a error too in this line:
\ZF\OAuth2\Doctrine\EventListener\DynamicMappingSubscriber:83

$clientIdField = $this->getMapping()->Client->mapping->client_id->name;

I solve here with this:

$clientIdField = $this->getMapping()->{'ZF\OAuth2\Doctrine\Mapper\Client'}->mapping->client_id->name;

I do not send you a pull request because these fixes require changes in the tests too.

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.