Coder Social home page Coder Social logo

zend-expressive-authentication-oauth2's Introduction

Logo

Welcome to the Zend Framework 3.0 Release!

RELEASE INFORMATION

Zend Framework 3.0.1dev

This is the first maintenance release for the Zend Framework 3 series.

DD MMM YYYY

UPDATES IN 3.0.1

Please see CHANGELOG.md.

SYSTEM REQUIREMENTS

Zend Framework 3 requires PHP 5.6 or later; we recommend using the latest PHP version whenever possible.

INSTALLATION

We no longer recommend installing this package directly. The package is a metapackage that aggregates all components (and/or integrations) originally shipped with Zend Framework; in most cases, you will want a subset, and these may be installed separately; see https://docs.zendframework.com/ for a list of available packages and installation instructions for each.

We recommend using either the zend-mvc skeleton application:

$ composer create-project zendframework/skeleton-application project

or the Expressive skeleton application:

$ composer create-project zendframework/zend-expressive-skeleton project

The primary use case for installing the entire framework is when upgrading from a version 2 release.

If you decide you still want to install the entire framework:

$ composer require zendframework/zendframework

GETTING STARTED

A great place to get up-to-speed quickly is the Zend Framework QuickStart.

The QuickStart covers some of the most commonly used components of ZF. Since Zend Framework is designed with a use-at-will architecture and components are loosely coupled, you can select and use only those components that are needed for your project.

MIGRATION

For detailed information on migration from v2 to v3, please read our Migration Guide.

COMPONENTS

This package is a metapackage aggregating the following components:

CONTRIBUTING

If you wish to contribute to Zend Framework, please read the CONTRIBUTING.md and CODE_OF_CONDUCT.md files.

QUESTIONS AND FEEDBACK

Online documentation can be found at https://docs.zendframework.com/. Questions that are not addressed in the manual should be directed to the relevant repository, as linked above.

If you find code in this release behaving in an unexpected manner or contrary to its documented behavior, please create an issue with the relevant repository, as linked above.

Reporting Potential Security Issues

If you have encountered a potential security vulnerability in Zend Framework, please report it to us at [email protected]. We will work with you to verify the vulnerability and patch it.

When reporting issues, please provide the following information:

  • Component(s) affected
  • A description indicating how to reproduce the issue
  • A summary of the security vulnerability and impact

We request that you contact us via the email address above and give the project contributors a chance to resolve the vulnerability and issue a new release prior to any public exposure; this helps protect Zend Framework users and provides them with a chance to upgrade and/or update in order to protect their applications.

For sensitive email communications, please use our PGP key.

LICENSE

The files in this archive are released under the Zend Framework license. You can find a copy of this license in LICENSE.md.

ACKNOWLEDGEMENTS

The Zend Framework team would like to thank all the contributors to the Zend Framework project; our corporate sponsor, Zend Technologies / Rogue Wave Software; and you, the Zend Framework user.

Please visit us sometime soon at http://framework.zend.com.

zend-expressive-authentication-oauth2's People

Contributors

ezimuel avatar froschdesign avatar geerteltink avatar jguittard avatar marc-mabe avatar marcguyer avatar michalbundyra avatar oqq avatar sheridans avatar sunspikes avatar thexpand avatar tux-rampage avatar weierophinney avatar wshafer 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

Watchers

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

zend-expressive-authentication-oauth2's Issues

"bin" or "scripts" for bin/generate-keys.php?

Should we have script bin/generate-keys.php in bin or scripts section in composer.json?

I think it should be in bin, and currently it is in scripts. If we have it in bin then will be available when we install package via composer in vendor/bin/.... When it is in scripts it is only available in that package.
When we change it to bin maybe we should also use another name, because this could be too generic, something with zend-/zf- maybe?

Incorrect permissions on windows during tests

Provide a narrative description of what you are trying to accomplish.

Code to reproduce the issue

Run composer test on windows

Expected results

Tests pass.

Actual results

  1. ZendTest\Expressive\Authentication\OAuth2\AuthorizationServerFactoryTest::testInvokeWithValidData
    Key file "file://~\Projects\zendframwork\zend-expressive-authentication-oauth2\test/TestAsset/private.key" permissions are not correct, should be 600 or 660 instead of 666

ResponsePrototypeTrait usage

In this repository we have file ResponsePrototypeTrait but it is not used here and instead ResponsePrototypeTrait from zend-expressive-authentication is used in two places.

Should we remove it them from this repository and use one from the main one or rather start using one from this repo?

Client name and client identifier are differents

In (ClientEntity, ClientRepository, ClientTrait, entityTrait) The code treats clientIdentifier === clientName,

OR , in "League\OAuth2\Server\Entities\ClientEntityInterface" , clientIdentifier and clientName are two different fields.

why not to seperate them as ligue-oauth2 do ?

what is the interest? can you answer me please?,
Maybe you have things to be planned.

AccessTokenRepository - Valid tokenid handling not present in oauth_access_tokens

Generate a tokenId at "/oauth2/access_token"

'grant_type' => 'client_credentials',
'client_id' => 'client_test',
'client_secret' => 'test',
'scope' => 'test',

Delete the id register from oauth_access_tokens, or recreate the database

Call some resource that will be validated by oAuth, passing the tokenId generated before

it will throw

TypeError raised in file /vendor/zendframework/zend-expressive-authentication-oauth2/src/Repository/Pdo/AccessTokenRepository.php line 118:
Message: array_key_exists() expects parameter 2 to be array, boolean given

I'd paste the isAccessTokenRevoked function with stating return value incorrectly assumes $row is an array, in the case entity doesn't exist in database should return true or throw an exception

Scopes table makes little sense.

As scopes are not really attached to anything, this table doesn't make much sense. It doesn't look like I can attach scopes to users or clients, so all we have is a table of valid scope names which doesn't do a whole lot for us.

I suggest we either do away with scopes, or allow scopes to be added to clients/users

Issues debugging

Code to reproduce the issue

this method blocks errors from being shown

    public function authenticate(ServerRequestInterface $request) : ?UserInterface
    {
        try {
            $result = $this->resourceServer->validateAuthenticatedRequest($request);
            $userId = $result->getAttribute('oauth_user_id', false);
            if (false !== $userId) {
                return $this->generateUser($userId, []);
            }
        } catch (OAuthServerException $exception) {
            return null;
        }
        return null;
    }

and then if I fix it and add

`throw $exception;`

into the catch, it runs...

    public static function accessDenied($hint = null, $redirectUri = null)
    {
        return new static(
            'The resource owner or authorization server denied the request.',

which still hides the actual error message.

I don't see any way to access that $hint value. So currently I have no way to troubleshoot why I am getting totally blank results on API call tests.

I changed the static() return to pass $hint and the error causing this scenario was

The JWT string must have two dots

but it will be the same issue with any error

Wish Item: Auth Aggrogate for Password Grant

Would be nice to be able to provide our own auth method for the password grant, while I could certainly pass in a new userRepository, it would be nice to be able to add an additional password verifier to the existing repo. Perhaps we could make this an aggrogate service, much like zend-auth uses?

Dependency bump

Bump the dependency version in which zend-expressive-authentication-oauth2 relies on zend-expressive-authentication.

Code to reproduce the issue

Composer file:

{
    ...
    "zendframework/zend-expressive-authentication": "^1.0.0",
    "zendframework/zend-expressive-authentication-oauth2": "^0.4.3"
}

Expected results

To be able to use the latest version zend-expressive-authentication.

Actual results

Composer requirements could not be resolved.

zend-expressive-authentication-oauth2 requires zend-expressive-authentication ^0.4.0

AuthenticationInterface service is missing when using oauth2 module with expressive 3

Sorry for opening this new issue but I really think it's a bug in the oauth2 module or an incomplete documentation.
I followed the instructions and figured out my problem: The app crashes with a ServiceNotCreatedException and the message "AuthenticationInterface service is missing". But if I make a print_r($container) in routes.php, the interface is correctly listed under aliases.

config/autoload/dependencies.global.php

<?php

declare(strict_types=1);

use Zend\Expressive\Authentication;

return [
    'dependencies' => [
        'aliases' => [
            Authentication\AuthenticationInterface::class => Authentication\OAuth2\OAuth2Adapter::class,
        ],
        'invokables' => [
        ],
        'factories'  => [
        ],
    ],
];

config/autoload/oauth2.global.php

<?php

declare(strict_types=1);

use League\OAuth2\Server\Grant;

return [
    'authentication' => [
        'private_key' => dirname(__DIR__) . '/../data/oauth/private.key',
        'public_key' => dirname(__DIR__) . '/../data/oauth/public.key',
        'encryption_key' => require dirname(__DIR__) . '/../data/oauth/encryption.key',

        'access_token_expire' => 'P1D',
        'refresh_token_expire' => 'P1M',
        'auth_code_expire' => 'PT10M',

        'pdo' => [
            'dsn' => sprintf(
                'mysql:dbname=%s;host=%s',
                false !== getenv('MYSQL_DB_NAME') ? getenv('MYSQL_DB_NAME') : '',
                false !== getenv('MYSQL_DB_HOST') ? getenv('MYSQL_DB_HOST') : ''
            ),
            'username' => false !== getenv('MYSQL_DB_USER') ? getenv('MYSQL_DB_USER') : '',
            'password' => false !== getenv('MYSQL_DB_PASS') ? getenv('MYSQL_DB_PASS') : '',
        ],

        'grants' => [
            Grant\ClientCredentialsGrant::class => Grant\ClientCredentialsGrant::class,
            Grant\PasswordGrant::class => Grant\PasswordGrant::class,
            Grant\AuthCodeGrant::class => Grant\AuthCodeGrant::class,
            Grant\ImplicitGrant::class => Grant\ImplicitGrant::class,
            Grant\RefreshTokenGrant::class => Grant\RefreshTokenGrant::class,
        ],
    ],
];

config/routes.php

<?php

declare(strict_types=1);

use MyProject\Api\Handler\HomePageHandler;
use MyProject\Api\Handler\PingHandler;
use Psr\Container\ContainerInterface;
use Zend\Expressive\Application;
use Zend\Expressive\Authentication\AuthenticationMiddleware;
use Zend\Expressive\Authentication\OAuth2\TokenEndpointHandler;
use Zend\Expressive\MiddlewareFactory;

return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
    $app->post('/oauth2/token', TokenEndpointHandler::class);

    $app->get('/', HomePageHandler::class, 'home');
    $app->get('/api/ping', [
        AuthenticationMiddleware::class,
        PingHandler::class,
    ], 'api.ping');
};

Provide a narrative description of what you are trying to accomplish.

Code to reproduce the issue

Expected results

Actual results

Script to generate keys writes to vendor dir

Provide a narrative description of what you are trying to accomplish.

Code to reproduce the issue

  1. Create a project
$ composer create-project zendframework/zend-expressive-skeleton oauth2-test
  1. Add zendframework/zend-expressive-authentication-oauth2 as a dependency
$ cd oauth2-test
$ composer require zendframework/zend-expressive-authentication-oauth2 dev-master
  1. Run the repo's generate-keys bin script per the installation docs:
$ php vendor/bin/generate-keys.php
Could not open input file: vendor/bin/generate-keys.php

... where is it?

$ find . -name '*generate-keys*'
./vendor/zendframework/zend-expressive-authentication-oauth2/bin/generate-keys.php

... try this:

$ ./vendor/zendframework/zend-expressive-authentication-oauth2/bin/generate-keys.php
-bash: ./vendor/zendframework/zend-expressive-authentication-oauth2/bin/generate-keys.php: Permission denied

... it's not executable, so:

$ php vendor/zendframework/zend-expressive-authentication-oauth2/bin/generate-keys.php
Private key stored in:
/Users/marcguyer/Documents/dev/marcguyer/oauth2-test/vendor/zendframework/zend-expressive-authentication-oauth2/data/private.key
Public key stored in:
/Users/marcguyer/Documents/dev/marcguyer/oauth2-test/vendor/zendframework/zend-expressive-authentication-oauth2/data/public.key
Encryption key stored in:
/Users/marcguyer/Documents/dev/marcguyer/oauth2-test/vendor/zendframework/zend-expressive-authentication-oauth2/data/encryption.key

... so that worked but placed the keys in vendor dir. Let's try running it with composer:

$ composer --working-dir=vendor/zendframework/zend-expressive-authentication-oauth2/ generate-keys
> php bin/generate-keys.php
Private key stored in:
/Users/marcguyer/Documents/dev/marcguyer/oauth2-test/vendor/zendframework/zend-expressive-authentication-oauth2/data/private.key
Public key stored in:
/Users/marcguyer/Documents/dev/marcguyer/oauth2-test/vendor/zendframework/zend-expressive-authentication-oauth2/data/public.key
Encryption key stored in:
/Users/marcguyer/Documents/dev/marcguyer/oauth2-test/vendor/zendframework/zend-expressive-authentication-oauth2/data/encryption.key

... same result

Expected results

Keys are expected to be written to the data dir of the parent application (./data). Ideally, I'd like to see it in a namespaced dir in ./data... e.g., ./data/zend-expressive-authentication-oauth2/

Actual results

Keys are written to vendor/zendframework/zend-expressive-authentication-oauth2/data/

/see #3 for a related issue

persistNewAccessToken and persistNewRefreshToken

  • AccessTokenRepository : Lines 71 and 72
    ':revoked' => (int)false,
    ':expires_at' => date("Y-m-d H:i:s", $accessTokenEntity->getExpiryDateTime()->getTimestamp())
  • RefreshTokenRepository : lines 32 and 33
    $sth->bindValue(':revoked', (int)false);
    $sth->bindValue(':expires_at', date("Y-m-d H:i:s", $refreshTokenEntity->getExpiryDateTime()->getTimestamp()));

i have to make that, to persist the record without error.

Thanks.

Improve docs - disable key file permission check

Hey,

I believe it would be great to update the docs with following or similar statement:

By default both key files are checked for correct permissions (chmod 600 or 660
is expected). In case the environment/operating system (e.g. Windows) does not 
support such a setting, the permission check can be disabled:


    // ...
    'private_key' => [
        'key_or_path' => __DIR__ . '/../data/oauth/private.key',
        'key_permissions_check' => false,
    ],
    // ...

This would help developers who are not using linux based OS etc. What do you think?

Thanks

Previous response bodies in $response->getBody()->getContent()

Provide a narrative description of what you are trying to accomplish.

$this->responsePrototype is not building a new response object for each response. So using Swoole or PHPReact results in previous responses bleeding into each other.

Code to reproduce the issue

$response = $this-handle($request);
$response = $this-handle($request);
$response->getBody()->getContent();

Expected results

Only one response per request

Actual results

Mutiple response bodies per request

Oauth Server ignores expires time on access tokens

Current implementation ignores expires time of the access token. Tokens that have expired are currently valid.

To reproduce:
Create an auth token. Updates it's expires_at column to something in the past. Try a restricted page.

Expected Result:
error for an invalid token

No /oauth route exist

After configuring Expressive 3 and oauth2 (0.4.0) with the actual docs, when i make a request for token i got a 404 error.
I selected zend-servicemanager, FastRoute in the default config.

Code to reproduce the issue

http -f POST localhost:8080/oauth grant_type=password client_id=client_test username=user_test password=test

HTTP/1.1 404 Not Found
Connection: close
Content-type: text/html; charset=UTF-8
Date: Fri, 23 Mar 2018 15:28:03 +0100
Host: localhost:8080
X-Powered-By: PHP/7.1.15-1+ubuntu16.04.1+deb.sury.org+2

Cannot POST http://localhost:8080/oauth

Expected results

JWT token

If i manually add a route in routes.php file, it is fine!

$app->route('/oauth', Zend\Expressive\Authentication\OAuth2\OAuth2Middleware::class, ['GET', 'POST'], 'oauth');

Getting an error while grant_type = password

Code to reproduce the issue

Using window platform while using grant_type = password getting an error json like
{"error":"unknown_error","message":"It was not possible to parse your key, reason: error:0906D06C:PEM routines:PEM_read_bio:no start line"}

Expected results

It should give me the response as mentioned in the OAuth 2.0 Server

Actual results

Getting an error json
{"error":"unknown_error","message":"It was not possible to parse your key, reason: error:0906D06C:PEM routines:PEM_read_bio:no start line"}

[documentation] Intro OAuth config defaults are incorrect

Error received when relying on config installation default locations for oauth key files.

What the documentation says it defaults to:

    'private_key'    => __DIR__ . '/../data/oauth/private.key',
    'public_key'     => __DIR__ . '/../data/oauth/public.key',
    'encryption_key' => require __DIR__ . '/../data/oauth/encryption.key',

What it actually defaults to:

    'private_key'    => __DIR__ . '/../data/private.key',
    'public_key'     => __DIR__ . '/../data/public.key',

See:

Documentation
Code

Configuration problem with latest expressive skeleton, HTTP 500

I'm very new in zend-expressive and used the skeleton app as entry point. Now I want to protect my API using zend-expressive-authentication-oauth2 and have some problems to get it working. The system is PHP 7.2 (Debian) and all packages installed via composer in the latest versions.
I followed the instructions to install and configure the module: I created the *.key files under data/oauth, used the SQL script to create the database tables and made the modifications in the app configs.
What happens is that I get an HTTP 500 error if I call the following URL in a browser:

example.com/api/ping

And the same if I post client credentials to the URL:

example.com/oauth2/token

So I guess there's something wrong with the configuration. Unfortunately the error page displays no concrete error message so debugging is quite difficult. But I try to show my files so exact as possible.

config/config.php

$aggregator = new ConfigAggregator([
    \Zend\Expressive\Authentication\ConfigProvider::class,
    // ...
    MyProject\Api\ConfigProvider::class,
    new PhpFileProvider(realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php'),
], $cacheConfig['config_cache_path']);

config/autoload/dependencies.global.php

<?php

declare(strict_types=1);

use Zend\Expressive\Authentication;

return [
    'dependencies' => [
        'aliases' => [
            Authentication\AuthenticationInterface::class => Authentication\OAuth2\OAuth2Adapter::class,
        ],
        'invokables' => [
        ],
        'factories'  => [
        ],
    ],
];

config/autoload/oauth2.global.php

<?php

declare(strict_types=1);

use League\OAuth2\Server\Grant;

return [
    'private_key' => dirname(__DIR__) . '/../data/oauth/private.key',
    'public_key' => dirname(__DIR__) . '/../data/oauth/public.key',
    'encryption_key' => require dirname(__DIR__) . '/../data/oauth/encryption.key',

    'access_token_expire' => 'P1D',
    'refresh_token_expire' => 'P1M',
    'auth_code_expire' => 'PT10M',

    'pdo' => [
        'dsn' => sprintf(
            'mysql:dbname=%s;host=%s',
            false !== getenv('MYSQL_DB_NAME') ? getenv('MYSQL_DB_NAME') : '',
            false !== getenv('MYSQL_DB_HOST') ? getenv('MYSQL_DB_HOST') : ''
        ),
        'username' => false !== getenv('MYSQL_DB_USER') ? getenv('MYSQL_DB_USER') : '',
        'password' => false !== getenv('MYSQL_DB_PASS') ? getenv('MYSQL_DB_PASS') : '',
    ],

    'grants' => [
        Grant\ClientCredentialsGrant::class => Grant\ClientCredentialsGrant::class,
        Grant\PasswordGrant::class => Grant\PasswordGrant::class,
        Grant\AuthCodeGrant::class => Grant\AuthCodeGrant::class,
        Grant\ImplicitGrant::class => Grant\ImplicitGrant::class,
        Grant\RefreshTokenGrant::class => Grant\RefreshTokenGrant::class,
    ],
];

config/autoload/pipeline.php

No modifications.

config/routes.php

<?php

declare(strict_types=1);

use MyProject\Api\Handler\HomePageHandler;
use MyProject\Api\Handler\PingHandler;
use Psr\Container\ContainerInterface;
use Zend\Expressive\Application;
use Zend\Expressive\Authentication\AuthenticationMiddleware;
use Zend\Expressive\Authentication\OAuth2\TokenEndpointHandler;
use Zend\Expressive\MiddlewareFactory;

return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
    $app->post('/oauth2/token', TokenEndpointHandler::class);

    $app->get('/', HomePageHandler::class, 'home');
    $app->get('/api/ping', [
        AuthenticationMiddleware::class,
        PingHandler::class,
    ], 'api.ping');
};

Provide a narrative description of what you are trying to accomplish.

Code to reproduce the issue

Expected results

Actual results

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.