Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Oauth2ServerBundle Return Invalid token #86

Open
TheEyes007 opened this issue Mar 16, 2022 · 2 comments
Open

Oauth2ServerBundle Return Invalid token #86

TheEyes007 opened this issue Mar 16, 2022 · 2 comments

Comments

@TheEyes007
Copy link

TheEyes007 commented Mar 16, 2022

Hello everybody,

En ----
I post here because I try to connect hwiBundle with thephpleague/oauth2-server-bundle and I have an error Invalid Token. In effect, I test in the bundle by dd and the oauth server return my login page (html) so invalid token.

FR ----
J'écris ici parce que je rencontre des difficultés à connecter le bundle oauth server avec mon client HWI. Mon client dit que mon token est invalid dans les logs symfony. J'ai voulu donc tester via le navigateur puis postman et le serveur me retourne une page html de formulaire login au lieu d'un token. Je suis sous Symfony 5.4. Voici les retours de mon navigateur.

I'm on symfony 5.4.

Header Location My connect : https://portail.test/authorize?response_type=code&client_id=225aea10a3a4f3f050116219d63140aa&scope=SUPER_USER&state=eyJjc3JmX3Rva2VuIjoiMWM1OTBhODAyMWMxNGU2YTkxY2ZiOGRiNmEzZTVjNjIifQ%253D%253D&redirect_uri=https%3A%2F%2Fclientsoauth.test%2Flogin%2Fcheck-custom

Header Location Authorize: https://clientsoauth.test/login/check-custom?code=def5020033892ce12a4a88267418da2413925e1227293da1f6ae9e90f930c1434019097c633bea94b662a53cbd7ef989a7dbcde36c0546d0baa99d5e86987883ef2adc161c7a2a92044e00784f9d2560cfbc184037c5134ddb54a20d9bd5187e974ca4c03715ba68f59dc51a6418948590f15f065d278e6242ba041afcdb693f4dfbcf2a56db29fbf758941efd4fd431887ff6ace4999dc18f8be250e2b8fd87be1b9e393f1c9166812bd8ec9c76d09f1d8affcac8220519031cdb6e7857062124993f9063d75a965d8306ad74d0fc575d0bb66a2ef03273c0647f4173ca46de96e58a2db0bf20456b3ee107e6d0198c01de88d3a2b41d012140c2f8ed8e0caa0655a2b9c90d23c68bc1eb7a75f31aa2d8d9f475b332f6441c6717cde3b3a4ecab1e613fd8ef9539acb1c26f3272c9c87464b187238c280940fbcfd2a0520f897d9f8284846bfe56b1f845a212464217bbadcae63b97626bb197453232d887854144c9dfb30b12dddc88be7ede9ce552549c707837bcf5993d06007141936b9b30d1442cb990b9d11984b90b46b0786b4dc69b8efc1df6850d8f13b4ceb0b5230d434e51aa6f39b39718&state=eyJjc3JmX3Rva2VuIjoiMWM1OTBhODAyMWMxNGU2YTkxY2ZiOGRiNmEzZTVjNjIifQ%253D%253D

Cookie CheckCustom : sf_redirect=%7B%22token%22%3A%22001b98%22%2C%22route%22%3A%22custom_login%22%2C%22method%22%3A%22GET%22%2C%22controller%22%3A%22n%5C%2Fa%22%2C%22status_code%22%3A302%2C%22status_text%22%3A%22Found%22%7D; path=/; secure; httponly; samesite=lax

En ----
So, I try to dd() in TokenController of the bundle but it seems controller is not used.

FR ----
J'ai essayé de faire des tests dans le TokenController pour voir comment il fonctionne et quelles classes ils utilisent mais il semble qu'il n'est pas utilisé lors des redirections des requêtes.

My yml league_oauth2_server.yml

league_oauth2_server:
  authorization_server: # Required
    private_key: 'D:\apps\toto\toto_Portail\certs\oauthserver.key' # Required, Example: /var/oauth/private.key
    private_key_passphrase: '@3O3E39EHD80'
    encryption_key: 'def00000cc93d67e8f289313a9ea381f7f1860a439f05777ae0b7e30fb7053957fd88adf980d3c0da011560baece72be2f0ea0d22722ea19ac524c905ca7d6c135ab88ba'
    encryption_key_type:  plain # One of "plain"; "defuse"
    access_token_ttl:     PT1H
    refresh_token_ttl:    P1M
    auth_code_ttl:        PT10M
    enable_client_credentials_grant: true
    enable_password_grant: true
    enable_refresh_token_grant: true
    enable_auth_code_grant: true
    require_code_challenge_for_public_clients: true
    enable_implicit_grant: true
    persist_access_token: true

  resource_server:      # Required
    public_key: 'D:\apps\toto\toto_Portail\certs\oauthserver_pub.key' # Required, Example: /var/oauth/public.key
  scopes:
    available: [EMAIL, PREFERENCES,SUPER_USER]
    default: [SUPER_USER]
  persistence:          # Required
    doctrine:
      entity_manager: default
  role_prefix:          ROLE_OAUTH2_
  client:
    classname:        League\Bundle\OAuth2ServerBundle\Model\Client

security.yml (oauth server)

security:
    enable_authenticator_manager: true
    role_hierarchy:
        ROLE_OAUTH2_SUPER_USER: [ROLE_OAUTH2_EMAIL, ROLE_OAUTH2_PREFERENCES]
    # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
        App\Entity\User:
            algorithm: auto

    # https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        api_token:
            pattern: ^/api/token$
            security: false
        api:
            pattern: ^/api
            security: true
            stateless: true
            oauth2: true
        main:
            lazy: true
            provider: app_user_provider
            form_login:
                # "login" is the name of the route created previously
                login_path: login
                check_path: login
                enable_csrf: true

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/authorize, roles: IS_AUTHENTICATED_REMEMBERED }
        - { path: ^/, roles: ROLE_USER }

hwi_oauth :

hwi_oauth:
    firewall_names: [secured_area]
    resource_owners:
        portail:
            type:                oauth2
            class:               \HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\GenericOAuth2ResourceOwner
            client_id:           '%env(resolve:OAUTH_CLIENT_ID)%'
            client_secret:       '%env(resolve:OAUTH_CLIENT_SECRET)%'
            access_token_url:    '%env(resolve:OAUTH_URL)%/token'
            authorization_url:   '%env(resolve:OAUTH_URL)%/authorize'
            infos_url:           '%env(resolve:OAUTH_URL)%/resource'
            scope:               "SUPER_USER"
            user_response_class: HWI\Bundle\OAuthBundle\OAuth\Response\PathUserResponse
            paths:
                identifier: username
                nickname:   nickname
                firstname:  first_name
                lastname:   last_name
                realname:   ["first_name", "last_name"]
                email:      email
            options:
                csrf: true
    http:
        client: httplug.client.hwi_special # Default to httplug.client.default

security.yml

security:
    # https://symfony.com/doc/current/security/experimental_authenticators.html
    # enable_authenticator_manager: false
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        app_user_provider:
            id: portail.user_provider
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        secured_area:
            anonymous: true
            oauth:
                resource_owners:
                    portail: "/login/check-custom"
                login_path:        /connect/portail
                use_forward:       false
                failure_path:      /login
                oauth_user_provider:
                    service: portail.user_provider



    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/connect/, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/dialog/, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin, role: ROLE_USER}
        - { path: ^/, role: ROLE_USER }

For info, Client works with FOSOAuthServerBundle but I don't want use on S5.4, I prefer League\Bundle\OAuth2ServerBundle.

Could you help me ?

Matthieu.

@TheEyes007
Copy link
Author

TheEyes007 commented Mar 28, 2022

Bonjour,

C'est corrigé en modifiant le security.yml

    api_token:
        pattern: ^/api/token$
        security: false

Devient
token:
pattern: ^/token
security: false

Désormais l'erreur vient de HWI
[2022-03-28T10:51:50.327574+02:00] security.INFO: Authentication request failed. {"exception":"[object] (Symfony\Component\Security\Core\Exception\AuthenticationException(code: 0): Response is not a valid JSON code. at D:\apps\toto\toto_ClientsOauth\vendor\hwi\oauth-bundle\OAuth\Response\AbstractUserResponse.php:131)"} []

Dans la configuration normal je devrais avoir :
[2022-03-15T15:35:30.773900+01:00] security.INFO: User has been authenticated successfully. {"username":"Admin"} []

Je poursuis mes investigation du pourquoi je n'ai pas ce JSON avec ce bundle et quelle méthode pour récupérer l'information.
Je ne sais pas trop quoi mettre dans le infos_url de HWI car je n'ai que deux routes (token et authorize de disponible).

Bonne journée.

@TheEyes007
Copy link
Author

Bonjour,

Finalement, en m'y remettant dessus, j'ai vu d'ou venait le soucis. Il faut créer un controller /api pour que l'authentification se fasse complètement coté client HWI.
En parcourant le bundle HWI coté client, j'ai pu voir que c'était le infos_url qu'il fallait analyser.

Dans la partie serveur oauth, j'ai paramétré ma route api dans mon controller.

`/**

  • Class ApiController
  • @Package App\Controller
    /
    class ApiController extends AbstractController
    {
    /
    *
    • @route("/api", name="app_api")
      */
      public function index(): Response
      {
      $user = $this->getUser();
      $userInfo = [];
      $userInfo['username'] = $user->getId();
      $userInfo['nickname'] = $user->getEmail();
      $userInfo['email'] = $user->getEmail();
      $userInfo['roles'] = $user->getRoles();

      return new JsonResponse($userInfo);
      }
      }`

Le fait de retourner le Json a resolu l'absence du {"username":"Admin"} précédent.

En espérant que ce retour puisse aider d'autres personnes qui découvre le Oauth coté serveur.

Bonne journée.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant