Giter VIP home page Giter VIP logo

mainick / keycloakclientbundle Goto Github PK

View Code? Open in Web Editor NEW
16.0 16.0 3.0 140 KB

The KeycloakClientBundle is bundle for Symfony, designed to simplify Keycloak integration into your application in Symfony and provide additional functionality for token management and user information access. It also includes a listener to verify the token on every request.

License: MIT License

PHP 100.00%
bundle keycloak-client oauth2 oauth2-client php symfony symfony-bundle

keycloakclientbundle's Introduction

Hi there 👋, I am Maico!

Senior Web Application Developer. I am a software engineer, a passionate coder, and a web developer. I am a fan of technology.

#php #symfony #javascript #reactjs


Follow me on

MaiNick Web - Blog LinkedIn Twitter Medium Dev.to Facebook


📜 Latest stories on Medium

📜 My recent articles on MaiNickWeb.com

📜 My recent posts on Dev.to


📌 Pinned Repositories


👨🏻‍💻 Programming Languages

PHPJavaScriptCSS3HTML5JsonMarkdown

💻 Framework and Libraries

SymfonyReactReact RouterReduxNodeJSFastifyNext JSjQueryBootstrapTailwindCSS

☁️ Version Control

GitGitHubBitbucket

💾 Databases

MySQLPostgresRedisSQLite

⚙️ ORM

DoctrineKnex.js

🔨 Testing

PHPUnit

⚙️ IDE & Editors

PhpStormSublime TextWebStorm

🦾 Tools

NPMYarnDockerWarpPostmanInsomniaJWTSwaggerElasticSearchJira

☁️ Web Services

NginxApache

keycloakclientbundle's People

Contributors

lsmith77 avatar mainick avatar

Stargazers

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

Watchers

 avatar  avatar

keycloakclientbundle's Issues

Error calling hasRole() and similar in KeycloakClient.php

I did some tests with this bundle, thanks for this bundle!

I get an error in this call (and similar ones) in:
vendor/mainick/keycloak-client-bundle/src/Provider/KeycloakClient.php

     public function hasRole(AccessTokenInterface $token, string $role): bool
     {
         $token_introspect = $this->verifyToken($token);
         //dd($token_introspect);

         return in_array($role, $token_introspect['roles'], true);
     }

The error is:
Cannot use object of type Mainick\KeycloakClientBundle\DTO\UserRepresentationDTO as array

and in fact the call to $this->verifyToken($token) returns an object of type UserRepresentationDTO, so the next instruction:

return in_array($role, $token_introspect['roles'], true);

triggers the error.

Furthermore, the UserRepresentationDTO class does not contain a "role" array, but three arrays referring to different types of roles returned by Keycloak:

realmRoles: count($realm_roles) ? $realm_roles : null,
clientRoles: count($client_roles) ? $client_roles : null,
applicationRoles: count($application_roles) ? $application_roles : null,

Is the hasRole() function in KeycloakClient.php just a suggestion to be further developed or did I miss some steps?

Thanks for your attention.

Add public function authenticateCodegrant()

Thanks for fixing the hasRole()!

This is not an issue, more like a little enhancement. I added a function to vendor/mainick/keycloak-client-bundle/src/Provider/KeycloakClient.php in order to get a Code Grant authentication (via authorization_code):

	public function authenticateCodegrant(): ?AccessTokenInterface
    {
        try {
            if (!isset($_GET['code'])) {
                // If we don't have an authorization code then get one
                $authUrl = $this->keycloakProvider->getAuthorizationUrl();
                $_SESSION['oauth2state'] = $this->keycloakProvider->getState();
                header('Location: '.$authUrl);
                exit;

            // Check given state against previously stored one to mitigate CSRF attack
            } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
                unset($_SESSION['oauth2state']);
                exit('Invalid state, make sure HTTP sessions are enabled.');
            } else {
                // Try to get an access token (using the authorization code grant)
                try {
                    $token = $this->keycloakProvider->getAccessToken('authorization_code', [
                        'code' => $_GET['code']
                    ]);
                } catch (Exception $e) {
                    exit('Failed to get access token: '.$e->getMessage());
                }
            }
            $accessToken = new AccessToken();
            $accessToken->setToken($token->getToken())
                ->setExpires($token->getExpires())
                ->setRefreshToken($token->getRefreshToken())
                ->setValues($token->getValues());

            $this->keycloakClientLogger->info('KeycloakClient::authenticateCodegrant', [
                'token' => $accessToken->getToken(),
                'expires' => $accessToken->getExpires(),
                'refresh_token' => $accessToken->getRefreshToken(),
            ]);

            return $accessToken;
        }
        catch (\Exception $e) {
            $this->keycloakClientLogger->error('KeycloakClient::authenticateCodegrant', [
                'error' => $e->getMessage(),
            ]);

            return null;
        }
    }

The function can be called just like the authenticate() but without user and password. Login is then handled directly from Keycloak:
$iamToken = $this->iamClient->authenticateCodegrant();

I'm sorry but I do not know PHPUnit, I tried to get this new function to pass the tests but I couldn't make it happen. According to your policy the test must be passed before sending a PR, so I'm posting it here hoping you find this function useful.

Symfony Security authenticator

Hello. Thank you for making this bundle.

Should there also be an authenticator for the Symfony security component - or am I missing something?

Thanks

Automate Configuration File and Environment Variable Setup with Symfony Flex

As per the README instructions, the current process requires manual configuration by creating a configuration file for the KeycloakClientBundle and adding environment variables before installing the package. This can be streamlined using the symfony recipes allow the automation of Composer packages configuration via the Symfony Flex Composer plugin.
Hence, I propose the following enhancements:

Automated Configuration File:

Symfony Flex can be leveraged to generate the mainick_keycloak_client.yaml configuration file in the config/packages directory. This file should contain the following default configuration structure:

# config/packages/mainick_keycloak_client.yaml

mainick_keycloak_client:
    keycloak:
        verify_ssl: '%env(bool:IAM_VERIFY_SSL)%'
        base_url: '%env(IAM_BASE_URL)%'
        realm: '%env(IAM_REALM)%'
        client_id: '%env(IAM_CLIENT_ID)%'
        client_secret: '%env(IAM_CLIENT_SECRET)%'
        redirect_uri: '%env(IAM_REDIRECT_URI)%'
        encryption_algorithm: '%env(IAM_ENCRYPTION_ALGORITHM)%'
        encryption_key: '%env(IAM_ENCRYPTION_KEY)%'
        encryption_key_path: '%env(IAM_ENCRYPTION_KEY_PATH)%'
        version: '%env(IAM_VERSION)%'

Automated Environment Variable Setup:

Symfony Flex can also add placeholders for the required environment variables in your project's environment file (e.g., .env or .env.local). The placeholders should look like this:

###> mainick/keycloak-client-bundle ###
IAM_VERIFY_SSL=true # Verify SSL certificate
IAM_BASE_URL='<your-base-server-url>'  # Keycloak server URL
IAM_REALM='<your-realm>' # Keycloak realm name
IAM_CLIENT_ID='<your-client-id>' # Keycloak client id
IAM_CLIENT_SECRET='<your-client-secret>' # Keycloak client secret
IAM_REDIRECT_URI='<your-redirect-uri>' # Keycloak redirect uri
IAM_ENCRYPTION_ALGORITHM='<your-algorithm>' # RS256, HS256, etc.
IAM_ENCRYPTION_KEY='<your-public-key>' # public key
IAM_ENCRYPTION_KEY_PATH='<your-public-key-path>' # public key path
IAM_VERSION='<your-version-keycloak>' # Keycloak version
###< mainick/keycloak-client-bundle ###

With these enhancements, the package's configuration and environment variable setup can be automated, simplifying the installation process.

Enhance JWT Token Introspection for HS256 Algorithm in 'HS256TokenDecoder.php'

Currently, the JWT token introspection process for tokens encoded with the HS256 algorithm is not as robust as desired. To improve the introspection capabilities, the src/Token/HS256TokenDecoder.php file needs to be modified. This issue proposes the following enhancements:

Enhancements

  1. Algorithm-Specific Introspection:
    Modify the src/Token/HS256TokenDecoder.php file to provide specific introspection logic for tokens encoded with the HS256 algorithm. This will ensure that the introspection process accurately handles tokens using this algorithm.

  2. Documentation Updates:
    Update the code comments and documentation within src/Token/HS256TokenDecoder.php to reflect the changes made, including any new introspection logic, error handling procedures, and the expected behavior for HS256 encoded tokens.

Expected Outcome:

After implementing these enhancements, the src/Token/HS256TokenDecoder.php file should be better equipped to handle and introspect JWT tokens encoded with the HS256 algorithm. This will improve the overall security and reliability of token processing within the application.

Note:

Please ensure that any code changes made are thoroughly tested to verify their correctness and compatibility with the HS256 encoded tokens. Additionally, consider any potential impacts on existing functionality and ensure that the documentation is updated accordingly.

Let me know if you need any further details or modifications to this description.

Implement Route Exclusion for Token Validation in 'TokenAuthListener.php'

Currently, the src/EventSubscriber/TokenAuthListener.php listener performs token validation on every request event, regardless of the route. To optimize the authentication process and exclude certain routes from token validation, this issue proposes the following enhancements:

Enhancements:

  1. Route Exclusion Configuration:
    Modify the TokenAuthListener.php listener to allow for configuration of routes that should be excluded from token validation. This can be achieved by defining a list of excluded routes in a configuration file.

  2. Conditional Validation:
    Implement conditional logic within the listener to check if the current route matches any of the excluded routes defined in the configuration. If a match is found, skip the token validation process for that particular request.

  3. Documentation Updates:
    Update the code comments and documentation within TokenAuthListener.php and the project's documentation to explain how to configure and utilize route exclusion for token validation. Provide examples and usage guidelines for clarity.

Expected Outcome:

After implementing these enhancements, the TokenAuthListener.php listener will have the ability to exclude specific routes from token validation, improving the efficiency and performance of token authentication. This will allow for better control over which routes require token validation and which can be exempted.

Note:

Please ensure that the configuration for route exclusion is flexible and easily maintainable. Consider the impact on security and verify that route exclusion does not compromise the security of sensitive routes.

Let me know if you need any further details or modifications to this description.

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.