Download the PHP package robsontenorio/laravel-keycloak-guard without Composer

On this page you can find all versions of the php package robsontenorio/laravel-keycloak-guard. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-keycloak-guard

 

Simple Keycloak Guard for Laravel

This package helps you authenticate users on a Laravel API based on JWT tokens generated from Keycloak Server.

Requirements

✔️ I`m building an API with Laravel.

✔️ I will not use Laravel Passport for authentication, because Keycloak Server will do the job.

✔️ The frontend is a separated project.

✔️ The frontend users authenticate directly on Keycloak Server to obtain a JWT token. This process have nothing to do with the Laravel API.

✔️ The frontend keep the JWT token from Keycloak Server.

✔️ The frontend make requests to the Laravel API, with that token.

💔 If your app does not match requirements, probably you are looking for https://socialiteproviders.com/Keycloak or https://github.com/Vizir/laravel-keycloak-web-guard

The flow

  1. The frontend user authenticates on Keycloak Server

  2. The frontend user obtains a JWT token.

  3. In another moment, the frontend user makes a request to some protected endpoint on a Laravel API, with that token.

  4. The Laravel API (through Keycloak Guard) handle it.

    • Verify token signature.
    • Verify token structure.
    • Verify token expiration time.
    • Verify if my API allows resource access from token.
  5. If everything is ok, then find the user on database and authenticate it on my API.

  6. Optionally, the user can be created / updated in the API users database.

  7. Return response

Install

Require the package

If you are using Lumen, register the provider in your boostrap app file bootstrap/app.php.
For facades, uncomment $app->withFacades(); in your boostrap app file bootstrap/app.php

Example configuration (.env)

Auth Guard

Changes on config/auth.php

Routes

Just protect some endpoints on routes/api.php and you are done!

Configuration

Keycloak Guard

⚠️ When editing .env make sure all strings are trimmed.

✔️ realm_public_key

Required.

The Keycloak Server realm public key (string).

How to get realm public key? Click on "Realm Settings" > "Keys" > "Algorithm RS256 (or defined under token_encryption_algorithm configuration)" Line > "Public Key" Button

✔️ token_encryption_algorithm

Default is RS256.

The JWT token encryption algorithm used by Keycloak (string).

✔️ load_user_from_database

Required. Default is true.

If you do not have an users table you must disable this.

It fetchs user from database and fill values into authenticated user object. If enabled, it will work together with user_provider_credential and token_principal_attribute.

✔️ user_provider_custom_retrieve_method

Default is null.

If you have an users table and want it to be updated (creating or updating users) based on the token, you can inform a custom method on a custom UserProvider, that will be called instead retrieveByCredentials and will receive the complete decoded token as parameter, not just the credentials (as default). This will allow you to customize the way you want to interact with your database, before matching and delivering the authenticated user object, having all the information contained in the (valid) access token available. To read more about custom UserProviders, please check Laravel's documentation about.

If using this feature, obviously, values defined for user_provider_credential and token_principal_attribute will be ignored.

✔️ user_provider_credential

Required. Default is username.

The field from "users" table that contains the user unique identifier (eg. username, email, nickname). This will be confronted against token_principal_attribute attribute, while authenticating.

✔️ token_principal_attribute

_Required. Default is preferred_username._

The property from JWT token that contains the user identifier. This will be confronted against user_provider_credential attribute, while authenticating.

✔️ append_decoded_token

Default is false.

Appends to the authenticated user the full decoded JWT token ($user->token). Useful if you need to know roles, groups and other user info holded by JWT token. Even choosing false, you can also get it using Auth::token(), see API section.

✔️ allowed_resources

Required.

Usually you API should handle one _resourceaccess. But, if you handle multiples, just use a comma separated list of allowed resources accepted by API. This attribute will be confronted against resource_access attribute from JWT token, while authenticating.

✔️ ignore_resources_validation

Default is false.

Disables entirely resources validation. It will ignore _allowedresources configuration.

✔️ leeway

Default is 0.

You can add a leeway to account for when there is a clock skew times between the signing and verifying servers. If you are facing issues like "Cannot handle token prior to " try to set it 60 (seconds).

✔️ input_key

Default is null.

By default this package always will look at first for a Bearer token. Additionally, if this option is enabled, then it will try to get a token from this custom request param.

API

Simple Keycloak Guard implements Illuminate\Contracts\Auth\Guard. So, all Laravel default methods will be available.

Default Laravel methods

Keycloak Guard methods

Token

token() Returns full decoded JWT token from authenticated user.

Role

hasRole('some-resource', 'some-role') _Check if authenticated user has a role on resourceaccess

hasAnyRole('some-resource', ['some-role1', 'some-role2']) _Check if the authenticated user has any of the roles in resourceaccess

Scope

Example decoded payload:

scopes() Get all user scopes

hasScope('some-scope') Check if authenticated user has a scope

hasAnyScope(['scope-a', 'scope-c']) Check if the authenticated user has any of the scopes

Acting as a Keycloak user in tests

As an equivalent feature like $this->actingAs($user) in Laravel, with this package you can use KeycloakGuard\ActingAsKeycloakUser trait in your test class and then use actingAsKeycloakUser() method to act as a user and somehow skip the Keycloak auth:

If you are not using keycloak.load_user_from_database option, set keycloak.preferred_username with a valid preferred_username for tests.

You can also specify exact expectations for the token payload by passing the payload array in the second argument:

$user argument receives a string identifier or an Eloquent model, identifier of which is expected to be the property referred in user_provider_credential config. Whatever you pass in the payload will override default claims, which includes aud, iat, exp, iss, azp, resource_access and either sub or preferred_username, depending on token_principal_attribute config.

Alternatively, payload can be provided in a class property, so it can be reused across multiple tests:

Priority is given to the claims in passed as an argument, so they will override ones in the class property. $user argument has the highest priority over the claim referred in token_principal_attribute config.

Contribute

You can run this project on VSCODE with Remote Container. Make sure you will use internal VSCODE terminal (inside running container).

Contact

Twitter @robsontenorio


All versions of laravel-keycloak-guard with dependencies

PHP Build Version
Package Version
Requires firebase/php-jwt Version ^6.3
php Version ^8.0
ext-openssl Version *
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package robsontenorio/laravel-keycloak-guard contains the following files

Loading the files please wait ....