Giter VIP home page Giter VIP logo

oauth2-bundle's People

Contributors

abraxas81 avatar ajgarlag avatar alexsegura avatar allypost avatar anthonymatignoncr avatar bmaximilian avatar carlos-ea avatar dkreuer avatar dsiemensma-move avatar elchris avatar franjo-zadelj-trikoder avatar gschafra avatar hypemc avatar kdckrs avatar nyholm avatar orkin avatar rjwebdev avatar spideyfusion avatar x-coder264 avatar yceruto 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  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  avatar  avatar

oauth2-bundle's Issues

Error in token controller

Hey
I got this error on calling token route:

Cannot autowire argument $serverRequest of "trikoder.oauth2.controller.token_controller:indexAction()": it references interface "Psr\Http\Message\ServerRequestInterface" but no such service exists. Did you create a class that implements this interface?

Attempted to load class "Psr17Factory" from namespace "Nyholm\Psr7\Factory".

Symfony 4. I recently encountered this problem, and solved it with this solution. This means I have been able to request a token successfully. When I now use it to call an endpoint, I receive this error:

Attempted to load class "Psr17Factory" from namespace "Nyholm\Psr7\Factory".

Stack trace:

in var/cache/dev/ContainerOERATu7/getSecurity_Authentication_Listener_Oauth2_ApiService.php (line 9)

use Symfony\Component\DependencyInjection\Exception\RuntimeException;

// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
// Returns the private 'security.authentication.listener.oauth2. api' shared service.

$a = new \Nyholm\Psr7\Factory\Psr17Factory();

return $this->privates['security.authentication.listener.oauth2. api'] = new \Trikoder\Bundle\OAuth2Bundle\Security\Firewall\OAuth2Listener(($this->services['security.token_storage'] ?? ($this->services['security.token_storage'] = new \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage())), ($this->privates['security.authentication.manager'] ?? $this->getSecurity_Authentication_ManagerService()), new \Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory($a, $a, $a, $a));

Hash client secrets

Hello,

As far as I can see, client secrets are stored in clear text in the database when using the Doctrine persistence.

Storing hashed credentials instead of clear text is a standard security practice. Is there any particular reason not to hash them?

Documentation is in Front of Development

The documentation shows the use of private_key_passphrase, but the development only uses this in dev-master version. The standard composer installation fails with the error:

Unrecognized option "private_key_passphrase" under "trikoder_oauth2.authorization_server". Available options are "access_token_ttl", "encryption_key", "private_key", "refresh_token_ttl".

Thanks, Craig

Deleting Oauth Clients throws Integrity Constraint Violation exception

When deleting a Client from the command line an exception is thrown:

php bin/console trikoder:oauth2:delete-client test

In AbstractMySQLDriver.php line 49:
                                                                                                                                                                                                                        
  An exception occurred while executing 'DELETE FROM oauth2_client WHERE identifier = ?' with params ["test"]:                                                                                                     
                                                                                                                                                                                                                        
  SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`db`.`oauth2_access_token`, CONSTRAINT `FK_454D9673C7440455` FOREIGN KEY (`c  
  lient`) REFERENCES `oauth2_client` (`identifier`))                                                                                                                                                                    
                                                                                                                                                                                                                        
In PDOStatement.php line 119:
                                                                                                                                                                                                                        
  SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`db`.`oauth2_access_token`, CONSTRAINT `FK_454D9673C7440455` FOREIGN KEY (`c  
  lient`) REFERENCES `oauth2_client` (`identifier`))                                                                                                                                                                    
                                                                                                                                                                                                                        
In PDOStatement.php line 117:
                                                                                                                                                                                                                        
  SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`db`.`oauth2_access_token`, CONSTRAINT `FK_454D9673C7440455` FOREIGN KEY (`c  
  lient`) REFERENCES `oauth2_client` (`identifier`))                                                                                                                                                                    
                                                                                                                                                                                                                        

This makes sense, because there are still records in the oauth2_access_token database. It could be solved 2 ways, by setting cascade DELETE on the entity, or by manually deleting all Access Token records with the related identifier from the database.

Deprecation warning in Doctrine2 Dbal Types

After latest Doctrine2 update, we're getting this deprecation warnings.

Deprecated: The type "oauth2_redirect_uri" was implicitly marked as commented due to the configuration. This is deprecated and will be removed in DoctrineBundle 2.0. Either set the "commented" attribute in the configuration to "false" or mark the type as commented in "Trikoder\Bundle\OAuth2Bundle\DBAL\Type\RedirectUri::requiresSQLCommentHint()."

Deprecated: The type "oauth2_scope" was implicitly marked as commented due to the configuration. This is deprecated and will be removed in DoctrineBundle 2.0. Either set the "commented" attribute in the configuration to "false" or mark the type as commented in "Trikoder\Bundle\OAuth2Bundle\DBAL\Type\Scope::requiresSQLCommentHint()

Edit: Looks like it's happening with all bundle entities

Client Model should not use Objects for Grants / Scopes / Request Uris

Hey,

the usage of Objects for Grants / Scopes / Request Uris in the Model for Clients causes me headaches at the moment. In context of the bundle, everything is fine. However, the bundle relies upon the magic conversion of said objects with __toString() by doctrine, which can not be relied upon. The Model should only use primitives or other Models.

Concretely, i am running into a lot of trouble when using your model in conjunction with API Platform, which relies on Symfonys Serializers.

Thanks for your hard work on this project, this is so far one of the only issues i ran into.

Greetings,

B

Invalid options in docs for authorization_server

Get following error when I run ./bin/console doctrine:schema:update --force

Unrecognized options "private_key_passphrase, encryption_key_type, enable_client_credentials_grant, enable_password_grant, enable_refresh_token_grant, auth_code_ttl" under "trikoder_oauth2.authorization_server". Available options are "access_token_ttl", "encryption_key", "private_key", "refresh_token_ttl"

List of available scopes

Hi! First of all thank you for this package. Works really great!

Currently is not possible to get list of configured scopes. If it's possible would be great to have Trikoder\Bundle\OAuth2Bundle\Manager\ScopeManagerInterface::list(): array method. My use case is GUI for managing for OAuth2 clients.

Unsupported Grant Type response on requesting with "client credentials"

I'm trying to connect to the /authorize route in my (Symfony 4) application

This is the request data I'm sending:

{
    "grant_type": "client_credentials",
    "client_id": "test",
    "client_secret": "*********",
    "scope": "read"
}

with Headers: Content-Type = application/x-www-form-urlencoded

The response I'm getting back is:

{
    "error": "unsupported_grant_type",
    "error_description": "The authorization grant type is not supported by the authorization server.",
    "hint": "Check that all required parameters have been provided",
    "message": "The authorization grant type is not supported by the authorization server."
}

with Response code 400 "bad request"

I've added my client with this create-client command php bin/console trikoder:o:create-client test ********** --scope=read --grant-type=client_credentials

running php bin/console trikoder:o:list-clients shows this list:

identifier secret scope redirect_uri grant_type
test ********** read client_credentials

What am I doing wrong, I have completely followed the installation guide.

Password grant user integration examples or further explaination?

Are there any examples, articles, or documentation which elaborates on the password grant handling user integration?

Is this integration supposed to allow tokens to be created based on existing user entities, without creating a oauth2 client?

Some context:

I'm using a pretty typical user system, where my User entity, where $user->email is the username. For the normal login, I'm using guard with a custom LoginFormAuthenticator to the UI.

Then there's an API which I want to use this oauth2 bundle for, where users can get a token with the same credentials they use to login with the UI, via password grant type.

I also want to allow them to generate new oauth2 clients for their apps which may also consume my API, via client_credentials grant type.

As far as the pasword grant type as described above, is this what the password grant handling is hinting that I can do? Any nudge in the right direction would be appreciated.

I've tried creating the UserResolveListener but it doesn't seem to be triggered but it's very likely that I'm not understanding how it is supposed to work.

Get connected user

Hello
I'm having some trouble using this bundle.
I can have a bearer token when sending a POST request to /token

{
"grant_type" : "client_credentials",
"client_id" : "john",
"client_secret": "8ba473ee0b9498ba1754e646304c6bbaeae8....",
"username" : "[email protected]",
"password" : "mypassword"
}

gives me :

{
    "token_type": "Bearer",
    "expires_in": 3600,
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp......"
}

Then I try to access a route and get the connected user :

    public function getUserAction()
    {
        dump($this->getUser());die;
    }

All I got is null meaning nobody is connected.

I tried to use the service trikoder.oauth2.league.repository.user_repository to be able to use getUserEntityByUserCredentials()

But all I got is this exception :

While discovering services from namespace "App", an error was thrown when processing the class "App\Console\ClassContextElementFactory": "Class MsgPhp\Domain\Infra\Console\Context\ClassContextElementFactoryInterface not found".

Then I added composer require msgphp/domain but same exception happens

Maybe I'm doing something wrong or I didn't understood something,

can you help me ?

Thanks

Passive authentication

I would like to create a route that is public, but still be able to use $this->getUser() which could returns User or null depending on if your security system detects a valid OAuth token or not. Does your bundle can be used that way ? This is the default behavior of the classic authentication system.

can't get commands

Hi guys
I can't get the commands you released 1 week ago, maybe you need to make a new release (1.1.1)?

thanks
M

Managers should only flush their entities

Currently, any manager implemented in this bundle calls flush(), ie. Manager/Doctrine/AccessTokenManager.php:35

It would be better to flush only one created entity.

Example from \Trikoder\Bundle\OAuth2Bundle\Manager\Doctrine\AccessTokenManager

Instead of:

public function save(AccessToken $accessToken): void
    {
        $this->entityManager->persist($accessToken);
        $this->entityManager->flush();
    }

use

public function save(AccessToken $accessToken): void
    {
        $this->entityManager->persist($accessToken);
        $this->entityManager->flush($accessToken);
    }

Release more frequently

There is no tagged release since 1.1.0 in January 2019 and master is ~90 commits ahead with lot of new things.

Consider tag and publish more frequently to help up keep our composer.json clean (no dev-master) and a easier way to check changes through time.

Thank you for your work :)

Need help with Authorization Code Grant

Hello,
I just started doing a few tests with your package, and it looks well built and polished!
I encountered an issue I did not manage to solve though: I cannot get the authorization to work because of an unsupported_grant_type error. The Authorization Code Grant should be feature since I read

API endpoint for client authorization and token issuing

on the repo's README.

I set up the bundle as stated in the readme, everything seems to work as intended.

However, when I do the following request:

GET http://api.mydomain.local/oauth/token?response_type=code&client_id=foo&state=5ca75bd30&scope=ifttt&redirect_uri=http://google.com

I get the error:

{
    "error": "unsupported_grant_type",
    "message": "The authorization grant type is not supported by the authorization server.",
    "hint": "Check that all required parameters have been provided"
}

I mean, I don't get why I'm getting this error when I specified response_type=code and client_id=xxx..

Did I miss something?

Thank you

ScopeManager missing for Doctrine

I'm getting an error when using scopes. When supplying any scope in my request, I get an invalid_scope error, even though it is defined for the client.

I think this is because the ScopeManager is missing for Doctrine. It uses the InMemory variant of the manager. The Doctrine variant does not exist at all.

Unable to get any response on token api - same 500 error

Hi,

Just installed this bundle and trying to get a token. Managed to update the schema and create a client. Everything seems fine and my application still works

When I call the api I always get this error:

{"code":500,"message":"Resources are not supported in serialized data. Path: Zend\\Diactoros\\Stream -> Zend\\Diactoros\\Response"}

I've tried a bit of debugging in the TokenController, but even if I simply return the new Response in the first line, it still gives this error.

Is there some dependency I'm missing or is it not working in php 7.2.12?
I checked composer.lock -- it has installed zendframework/zend-diactoros 1.8.6 and trikoder/oauth2-bundle v1.1.0 and league/oauth2-server 7.2.0.

A Token was not found in the TokenStorage

Hello,

I am trying to implement your library in a project, an I'm unable to get it working.
I can get an access token by going to a /token url, but after, when passing this token to my API's routes, I get a 401 unauthorized response.

When going to the symfony profiler, I can see that a AuthenticationCredentialsNotFoundException is thrown.

Here is my configuration :

  • Symfony 4.2.3
  • php 7.2.15

security.yaml :

security:
    providers:
        app_user_provider:
            entity:
                class: Trikoder\Bundle\OAuth2Bundle\Security\Authentication\Provider\OAuth2Provider
    firewalls:
        api_token:
            pattern: ^/api/token$
            security: false
        api:
            pattern: ^/api
            security: true
            stateless: true
            oauth2: true

        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: true

trikoder_oauth2.yaml :

trikoder_oauth2:

    authorization_server:

        # Full path to the private key file.
        # How to generate a private key: https://oauth2.thephpleague.com/installation/#generating-public-and-private-keys
        private_key: "%kernel.root_dir%/../var/oauth/private.key"

        # The string used as an encryption key.
        # How to generate an encryption key: https://oauth2.thephpleague.com/installation/#string-password
        encryption_key: "generated as phpleague doc says"

        # How long the issued access token should be valid for.
        # The value should be a valid interval: http://php.net/manual/en/dateinterval.construct.php#refsect1-dateinterval.construct-parameters
        access_token_ttl: PT1H

        # How long the issued refresh token should be valid for.
        # The value should be a valid interval: http://php.net/manual/en/dateinterval.construct.php#refsect1-dateinterval.construct-parameters
        refresh_token_ttl: P1M

    resource_server:

        # Full path to the public key file
        # How to generate a public key: https://oauth2.thephpleague.com/installation/#generating-public-and-private-keys
        public_key: "%kernel.root_dir%/../var/oauth/public.key"

    # Scopes that you wish to utilize in your application.
    # This should be a simple array of strings.
    scopes: []

    # Configures different persistence methods that can be used by the bundle for saving client and token data.
    # Only one persistence method can be configured at a time.
    persistence:

        doctrine:

            # Name of the entity manager that you wish to use for managing clients and tokens.
            entity_manager: default # Required

        #in_memory: ~

I made a chmod -R a+rwx on my var/oauth folder.

Am I missing something ?

Thanks in advance

Dependency on a non-existent service "app.repository.user_repository"

Using Symfony 4, I'm setting up password grant handling following these suggestions. When I make a call to /token, I get the following error:

The service "App\EventListener\UserResolveListener" has a dependency on a non-existent service "app.repository.user_repository".

which relates to the arguments section in services.yaml:

App\EventListener\UserResolveListener:
    arguments:
        - '@app.repository.user_repository'

The same format for type of response

For now we have a different response format
sometimes it is {"error": "...." ....}
sometimes - The resource server rejected the request.

It is not good for client(

maybe we have to stick to response like {"error": "...." ....} for all cases?

[Easy pick] Use FQCN for service ids

All services should be using FQCN (fully qualified class names (namespace + class)) as their service ids.

We could add aliases if we really wanted to keep our sf3.x standard.

    Trikoder\Bundle\OAuth2Bundle\Converter\UserConverter: '@trikoder.oauth2.converter.user_converter'

Need help with authorization grant flow

Hi guys,

I try to set up this bundle with SF4.2 and FOS Userbundle. I have the password flow and the client credentials flow working, But somehow I cannot get the authorization code grant working. I'm testing it using Postman. Do you guys have a demo application, or can you review these snippets? thanks a lot

composer.json

 "trikoder/oauth2-bundle": "dev-master"

For the password flow I implemented the UserResolveListener

App\EventListener\UserResolveListener:
        arguments:
            - '@fos_user.user_provider.username'
            - '@security.password_encoder'
        tags:
            - { name: kernel.event_listener, event: trikoder.oauth2.user_resolve, method: onUserResolve }

routes.yml

oauth2:
  resource: '@TrikoderOAuth2Bundle/Resources/config/routes.xml'
  prefix: /oauth/v2

trikoder_oauth2.yml: I added enable_refresh_token_grant: true, Is that valid?

trikoder_oauth2:

  authorization_server:
    private_key: '%kernel.project_dir%/var/private.key'
    encryption_key: '+Ht5kEwG2bAlCKSs13LPu51BCyu+643PKBRdnCc1JWY='
    access_token_ttl: PT1H
    refresh_token_ttl: P1M
    enable_client_credentials_grant: true
    enable_password_grant: true
    enable_refresh_token_grant: true # I added this myself. Is this valid?
    enable_auth_code_grant: true
    auth_code_ttl: PT10M

  resource_server:
    public_key: '%kernel.project_dir%/var/public.key'

  scopes: ['read']

  persistence:
    doctrine:
      entity_manager: default # Required

  exception_event_listener_priority: 10

Curl request ( I use Postman)

curl -X POST \
  http://127.0.0.1:8000/oauth/v2/authorize \
  -H 'Accept: */*' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Host: 127.0.0.1:8000' \
  -H 'Postman-Token: 8e0360e7-dbf6-48be-b090-08d2cc89d7df,724f973b-44cc-43c6-b799-a394b6017e2c' \
  -H 'User-Agent: PostmanRuntime/7.15.0' \
  -H 'accept-encoding: gzip, deflate' \
  -H 'cache-control: no-cache' \
  -H 'content-length: 663' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -H 'cookie: PHPSESSID=tk5c6pb1evmsjskg2n8rdstd58' \
  -b PHPSESSID=tk5c6pb1evmsjskg2n8rdstd58 \
  -F response_type=code \
  -F client_id=de7a2a311699b6636566610ebfc01449 \
  -F redirect_uri=http://127.0.0.1:4200 \
  -F state=lololol \
  -F scope=read

Response

{
    "error": "unsupported_grant_type",
    "error_description": "The authorization grant type is not supported by the authorization server.",
    "hint": "Check that all required parameters have been provided",
    "message": "The authorization grant type is not supported by the authorization server."
}

composer test failed

Hi,

I tried to install the projet using your instructions (branch master) :

dev/bin/docker-compose build --build-arg PHP_VERSION=7.3
dev/bin/php composer install
dev/bin/php composer test

But the tests failed with this message :

`Fatal error: Cannot make static method Symfony\Bundle\FrameworkBundle\Test\WebTestCase::getClient() non static in class Trikoder\Bundle\OAuth2Bundle\Tests\Acceptance\DeleteClientCommandTest in /app/src/Tests/Acceptance/DeleteClientCommandTest.php on line 73

Call Stack:
0.0001 403584 1. {main}() /app/src/vendor/phpunit/phpunit/phpunit:0
0.0046 1102840 2. PHPUnit\TextUI\Command::main() /app/src/vendor/phpunit/phpunit/phpunit:61
0.0047 1102952 3. PHPUnit\TextUI\Command->run() /app/src/vendor/phpunit/phpunit/src/TextUI/Command.php:160
0.0047 1102952 4. PHPUnit\TextUI\Command->handleArguments() /app/src/vendor/phpunit/phpunit/src/TextUI/Command.php:168
0.0095 1486096 5. PHPUnit\Util\Configuration->getTestSuiteConfiguration() /app/src/vendor/phpunit/phpunit/src/TextUI/Command.php:909
0.0333 2806504 6. PHPUnit\Util\Configuration->getTestSuite() /app/src/vendor/phpunit/phpunit/src/Util/Configuration.php:909
0.0356 2821184 7. PHPUnit\Framework\TestSuite->addTestFiles() /app/src/vendor/phpunit/phpunit/src/Util/Configuration.php:1044
0.0628 3275824 8. PHPUnit\Framework\TestSuite->addTestFile() /app/src/vendor/phpunit/phpunit/src/Framework/TestSuite.php:439
0.0628 3275824 9. PHPUnit\Util\FileLoader::checkAndLoad() /app/src/vendor/phpunit/phpunit/src/Framework/TestSuite.php:347
0.0629 3276032 10. PHPUnit\Util\FileLoader::load() /app/src/vendor/phpunit/phpunit/src/Util/FileLoader.php:47`

I suppose the issue comes from me but I can't find what I did wrong, could you help me ?

A Token was not found in the TokenStorage.

Hi,

i have installed this bundle and trying to get a token. As token generated fine but whenever i call Api with that token in header, this give me blank screen with with a status 401. Is this some kind of my configuration issue or compatibility.
i use postman for api call.
PHP : 7.2
Symfony : 4.2
Ubantu : 14.4

regards
shoaib

Authorize always go to login form

Hi, I need help please.
I'm trying to implement Authorization grant flow.
Everything is working for me.
The problem is that when accessing the authorize uri, i'm redirected to login page even if I'm already logedin.

security:
    encoders:
        App\Entity\User:
            algorithm: auto
    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        api:
            pattern: ^/api
            security: true
            stateless: true
            oauth2: true
        main:
            pattern: ^/
            anonymous: ~
            guard:
                authenticators:
                    - App\Security\FormLoginAuthenticator
            logout:
                path: main_logout

    access_control:
        - { path: ^/authorize, roles: IS_AUTHENTICATED_REMEMBERED }
        - { path: ^/token, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, roles: IS_AUTHENTICATED_REMEMBERED }

Thanks

Add strict scope mode and scope inheritance in non strict mode

Requested token should be validated against scopes defined on client.
If no scopes are requested they should be inherited from client scopes.

Proposed behavior for each use case:

Storage Client Request Token
A, B, C A A / Invalid scope
A, B, C A A A
A, B, C A B Invalid scope
A, B, C A F Invalid scope
A, B, C F * Invalid scope
A, B, C A A / Invalid scope
* Invalid scope
A,B, C A, B A,B / Invalid scope

For examples that are defined with / (A / Invalid scope) - exact behavior would be defined through configuration. If strict scope behaviour is set to true Invalid scope exception is thrown, otherwise scope is inherited from client / storage.

Symfony 4.3 deprecations

Upgrading to Symfony 4.3 gives the following deprecation errors:

The "Trikoder\Bundle\OAuth2Bundle\Event\ScopeResolveEvent" class extends "Symfony\Component\EventDispatcher\Event" that is deprecated since Symfony 4.3, use "Symfony\Contracts\EventDispatcher\Event" instead.

The "Trikoder\Bundle\OAuth2Bundle\Event\UserResolveEvent" class extends "Symfony\Component\EventDispatcher\Event" that is deprecated since Symfony 4.3, use "Symfony\Contracts\EventDispatcher\Event" instead.

The "Trikoder\Bundle\OAuth2Bundle\Security\Firewall\OAuth2Listener" class implements "Symfony\Component\Security\Http\Firewall\ListenerInterface" that is deprecated since Symfony 4.3, turn listeners into callables instead.

Getting `unsupported_grant_type` due to `$request->getParsedBody()` being empty

I've seen some issues raised with regards to unsupported_grant_type but it didn't solve my problem so I posted another one.

Composer

"symfony/symfony": "3.4.*",
"trikoder/oauth2-bundle": "^1.1",

Request

curl --request POST \
  --url https://localhost:8080/oauth/token \
  --header 'content-type: application/json' \
  --data '{
    "grant_type": "password",
    "client_id": "CLIENT_ID",
    "client_secret": "SECRET",
    "username": "[email protected]",
    "password": "password"
}' --insecure

Response

{"error":"unsupported_grant_type","message":"The authorization grant type is not supported by the authorization server.","hint":"Check that all required parameters have been provided"}

I saw the cause in vendor/league/oauth2-server/src/Grant/AbstractGrant.php where (array) $request->getParsedBody() returns null anywhere it's used. Changing it to (array) json_decode($request->getBody()) returns the JSON values as array. I know, it's a dependency of this package but I'm just checking if anyone got a solution for this or maybe I'm doing the request wrong.

Should the enabled grant types be configurable?

Hello,

I am currently in the process of deciding to use this bundle or directly the underlying library from the PHP league.

The issues that I have are:

  • I would need to configure which grant types are enabled. I do not think it is possible a the moment since they are enabled in the bundle extension.
  • I would need to override the password grant type with a custom one since the provided password grant is not flexible enough for us: we would need more than username and password in order to authenticate users. At the moment, the only way I can imagine to do that is to override the service league.oauth2.server.grant.password_grant and hope it still works when the bundle gets updated.
  1. Do you think that it would be a good idea to make the enabled grant types configurable?
  2. Would you consider a pull request about this?

Kind regards,

Guillaume.

The authorization grant type is not supported by the authorization server

Hi, thanks for this bundle.

I try to use it with symfony 4.2

composer.json:

  "trikoder/oauth2-bundle": "dev-master",
  "symfony/psr-http-message-bridge": "^1.2",
  "nyholm/psr7": "^1.1",
  "sensio/framework-extra-bundle": "^5.1",

security.yml

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

    firewalls:
        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false

        api_token:
            pattern: ^/token$
            security: false

        oauth_authorize: # here we handle the GRANT_TYPE_AUTH_CODE
            pattern: ^/authorize
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
                login_path: fos_user_security_login
                check_path: fos_user_security_check
            anonymous: true
            logout:
                path:                       fos_user_security_logout
                target:                     fos_user_security_login

        api: # the resource server: should be protected
            pattern: ^/api
            security: true
            stateless: true
            oauth2: true
            provider: fos_userbundle
            anonymous:  false # can be omitted as its default value

    access_control:
        - { path: ^/authorize, roles: IS_AUTHENTICATED_REMEMBERED }

Bundle is enabled, I can access the routes and run the commands.

My issue: I cannot get a token:

POST http://127.0.0.1:8000/token?client_id=de7a2a311699b6636566610ebfc01449&client_secret=94a8555796d6d78e1a050c9b3bbca4dc0f0d9d2e172b9e87a391b90f76e965a8d818314175ea7136d266fac07d2720fc401420df8b0c5f3e05b1711c39c154b9&grant_type=client_credentials&scope=read 

gives:

{
    "error": "unsupported_grant_type",
    "error_description": "The authorization grant type is not supported by the authorization server.",
    "hint": "Check that all required parameters have been provided",
    "message": "The authorization grant type is not supported by the authorization server."
}

Permission request page

When authentication is using the grant type authorization_code, the user should be redirected after loging in succesfully to a page where permissions are asked to the user.

If the user allows the application using his login data, he should be redirected to the original application where he will be logged in to. If he doesn't give permissions, the user should be redirected to the application without being logged in.

For example: https://developer.okta.com/blog/2018/04/10/oauth-authorization-code-grant-type#get-the-users-permission

Command clear-expired-tokens and foreign key constraint fails

This command makes no sense.
There will be exception "SQLSTATE[23000]: Integrity constraint violation:" when you try remove from access_token when there are related records in refresh_token table.
You can't remove access_token without removing refresh_token first, so you have to wait until refresh_token expires.
So only command for removing from refresh_token works, but not from access_token.
This command should be changes so you can only run something like this:

  • get access_token from refresh_token table where expired
  • delete from refresh_token table where expired
  • delete from access_token table where identity = access_token from refresh_token table

Add ability to override persisters in different environment

Currently, when you define persisters in config.yml (ie doctrine), and define a different one in config_test.yml (ie in_memory), you end up having more than one persister in merged config. This is not supported and an exception is raised in TrikoderOAuth2Extension::configurePersistence.

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.