Keycloak Web Guard for Laravel allow you authenticate users with Keycloak Server

Overview

Packagist Downloads Packagist Version (including pre-releases)

Keycloak Web Guard for Laravel

This packages allow you authenticate users with Keycloak Server.

It works on front. For APIs we recommend laravel-keycloak-guard.

Requirements

  • Have a Keycloak Server.
  • Have a realm configured and a client that accepts authentication.

Support

This package was tested with:

  • Laravel: 9
  • Keycloak: 12.0.4

Any other version is not guaranteed to work.

The flow

  1. User access a guarded route and is redirected to Keycloak login.
  2. User signin and obtains a code.
  3. He's redirected to callback page and we change the code for a access token.
  4. We store it on session and validate user.
  5. User is logged.
  6. We redirect the user to "redirect_url" route (see config) or the intended one.

Install

Require the package

composer require ydigitalmedia/keycloak-laravel-web-guard

If you want to change routes or the default values for Keycloak, publish the config file:

php artisan vendor:publish  --provider="YDigitalMedia\KeycloakWebGuard\KeycloakWebGuardServiceProvider"

Configuration

After publishing config/keycloak-web.php file, you can change the routes:

'redirect_url' => '/admin',

'routes' => [
    'login' => 'login',
    'logout' => 'logout',
    'register' => 'register',
    'callback' => 'callback',
]

Change any value to change the URL.

Other configurations can be changed to have a new default value, but we recommend to use .env file:

  • KEYCLOAK_BASE_URL

The Keycloak Server url. Generally is something like: https://your-domain.com/auth.

  • KEYCLOAK_REALM

The Keycloak realm. The default is master.

  • KEYCLOAK_REALM_PUBLIC_KEY

The Keycloak Server realm public key (string).

In dashboard go to: Keycloak >> Realm Settings >> Keys >> RS256 >> Public Key.

  • KEYCLOAK_CLIENT_ID

Keycloak Client ID.

In dashboard go to: Keycloak >> Clients >> Installation.

  • KEYCLOAK_OPERATOR

Keycloak Operator.

Can by wildfly or quarkus (quarkus is the default one).

  • KEYCLOAK_CLIENT_INTERNAL_ID

Keycloak Client Internal ID.

In dashboard go to: Keycloak >> Clients and check url for the client ID.

  • KEYCLOAK_CLIENT_SECRET

Keycloak Client Secret. If empty we'll not send it to Token Endpoint.

In dashboard go to: Keycloak >> Clients >> Installation.

  • KEYCLOAK_CACHE_OPENID

We can cache the OpenId Configuration: it's a list of endpoints we require to Keycloak.

If you activate it, remember to flush the cache when change the realm or url.

Just add the options you would like as an array to the" to "Just add the options you would like to guzzle_options array on keycloak-web.php config file. For example:

Laravel Auth

You should add Keycloak Web guard to your config/auth.php.

Just add keycloak-web to "driver" option on configurations you want.

As my default is web, I add to it:

'guards' => [
    'web' => [
        'driver' => 'keycloak-web',
        'provider' => 'users',
    ],

    // ...
],

And change your provider config too:

'providers' => [
    'users' => [
        'driver' => 'keycloak-users',
        'model' => YDigitalMedia\KeycloakWebGuard\Models\KeycloakUser::class,
    ],

    // ...
]

Note: if you want use another User Model, check the FAQ How to implement my Model?.

API

We implement the Illuminate\Contracts\Auth\Guard. So, all Laravel default methods will be available.

Ex: Auth::user() returns the authenticated user.

Roles

You can check user has a role simply by Auth::hasRole('role');

This method accept two parameters: the first is the role (string or array of strings) and the second is the resource.

If not provided, resource will be the client_id, which is the regular check if you authenticating into this client to your front.

Keycloak Web Gate

You can use Laravel Authorization Gate to check user against one or more roles (and resources).

For example, in your Controller you can check one role:

if (Gate::denies('keycloak-web', 'manage-account')) {
  return abort(403);
}

Or multiple roles:

if (Gate::denies('keycloak-web', ['manage-account'])) {
  return abort(403);
}

And roles for a resource:

if (Gate::denies('keycloak-web', 'manage-account', 'another-resource')) {
  return abort(403);
}

This last use is not trivial, but you can extend the Guard to request authentication/authorization to multiple resources. By default, we request only the current client.

Keycloak Can Middleware

If you do not want to use the Gate or already implemented middlewares, you can check user against one or more roles using the keycloak-web-can Middleware.

Add this to your Controller's __construct method:

$this->middleware('keycloak-web-can:manage-something-cool');

// For multiple roles, separate with '|'
$this->middleware('keycloak-web-can:manage-something-cool|manage-something-nice|manage-my-application');

This middleware works searching for all roles on default resource (client_id).

You can extend it and register your own middleware on Kernel.php or just use Auth::hasRole($roles, $resource) on your Controller.

FAQ

How to implement my Model?

We registered a new user provider that you configured on config/auth.php called "keycloak-users".

In this same configuration you setted the model. So you can register your own model extending YDigitalMedia\KeycloakWebGuard\Models\KeycloakUser class and changing this configuration.

You can implement your own User Provider: just remember to implement the retrieveByCredentials method receiving the Keycloak Profile information to retrieve a instance of model.

Eloquent/Database User Provider should work well as they will parse the Keycloak Profile and make a "where" to your database. So your user data must match with Keycloak Profile.

I cannot find my login form.

We register a login route to redirect to Keycloak Server. After login we'll receive and proccess the token to authenticate your user.

There's no login/registration form.

How can I protect a route?

Just add the keycloak-web middleware:

// On RouteServiceProvider.php for example

Route::prefix('admin')
  ->middleware('keycloak-web')
  ->namespace($this->namespace)
  ->group(base_path('routes/web.php'));

// Or with Route facade in another place

Route::group(['middleware' => 'keycloak-web'], function () {
    Route::get('/admin', 'Controller@admin');
});

Where the access/refresh tokens and state are persisted?

On session. We recommend implement the database driver if you have load balance.

What's a state?

State is a unique and non-guessable string used to mitigate CSRF attacks.

We associate each authentication request about to be initiated with one random state and check on callback. You should do it if you are extending/implementing your own Auth controller.

Use KeycloakWeb::saveState() method to save the already generated state to session and KeycloakWeb::validateState() to check the current state against the saved one.

I'm having problems with session (stuck on login loop)

For some reason Laravel can present a problem with EncryptCookies middleware changing the session ID.

In this case, we will always try to login, as tokens cannot be retrieved.

You can remove session_id cookie from encryption:

disableFor(config('session.cookie')); } } ">
// On your EncryptCookies middleware

class EncryptCookies extends Middleware
{
    protected $except = [];

    public function __construct(EncrypterContract $encrypter)
    {
        parent::__construct($encrypter);

        /**
         * This will disable in runtime.
         *
         * If you have a "session.cookie" option or don't care about changing the app name
         * (in another environment, for example), you can only add it to "$except" array on top
         */
        $this->disableFor(config('session.cookie'));
    }
}

My client is not public.

If your client is not public, you should provide a KEYCLOAK_CLIENT_SECRET on your .env.

How can I override the default Guzzle options?

In some use cases you may need to override the default Guzzle options - likely either to disable SSL verification or to set a Proxy to route all requests through.

Every [http://docs.guzzlephp.org/en/stable/request-options.html](Guzzle Request Option) is supported and is passed directly to the Guzzle Client instance.

Just add the options you would like to guzzle_options array on keycloak-web.php config file. For example:

'guzzle_options' => [
    'verify' => false
]

Developers

  • Bruno Pereira
You might also like...
Associate users with roles and permissions
Associate users with roles and permissions

Associate users with permissions and roles Sponsor If you want to quickly add authentication and authorization to Laravel projects, feel free to check

CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

Two-Factor Authentication for all your users out-of-the-box.

Two Factor On-premises Two-Factor Authentication for all your users out of the box. use Illuminate\Support\Facades\Auth; use Laragear\TwoFactor\TwoFac

A Native PHP MVC With Auth. If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo.

If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo. Auth system is implemented. Works with bootstrap 5. Composer with autoload are implemented too for future composer require.

A simple library to work with JSON Web Token and JSON Web Signature

JWT A simple library to work with JSON Web Token and JSON Web Signature based on the RFC 7519. Installation Package is available on Packagist, you can

PHP server built using laravel framework.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use

Introduction Laravel Passport is an OAuth2 server and API authentication package that is simple and enjoyable to use. Official Documentation Documenta

A spec compliant, secure by default PHP OAuth 2.0 Server

PHP OAuth 2.0 Server league/oauth2-server is a standards compliant implementation of an OAuth 2.0 authorization server written in PHP which makes work

documentation for the oauth2-server-php library

OAuth2 Server PHP Documentation This repository hosts the documentation for the oauth2-server-php library. All submissions are welcome! To submit a ch

Releases(v1.1.6)
Owner
YDigital Media
YDigital Media develops solutions for the connected world, with a mission to help businesses increase sales, productivity, and customer engagement.
YDigital Media
phpCAS is an authentication library that allows PHP applications to easily authenticate users via a Central Authentication Service (CAS) server.

phpCAS is an authentication library that allows PHP applications to easily authenticate users via a Central Authentication Service (CAS) server.

Apereo Foundation 780 Dec 24, 2022
EAuth extension allows to authenticate users by the OpenID, OAuth 1.0 and OAuth 2.0 providers

EAuth extension allows to authenticate users with accounts on other websites. Supported protocols: OpenID, OAuth 1.0 and OAuth 2.0.

Maxim Zemskov 330 Jun 3, 2022
Laravel Auth guard for FusionAuth JWT

Laravel FusionAuth JWT Implement an Auth guard for FusionAuth JWTs in Laravel. It ships with also a middleware to check against the user role. Install

Theraloss 7 Feb 21, 2022
HTTP Basic Auth Guard for Lumen 5.x

HTTP Basic Auth Guard HTTP Basic Auth Guard is a Lumen Package that lets you use basic as your driver for the authentication guard in your application

Christopher Lass 40 Nov 11, 2022
this is a semester project using Laravel, this app allow user to keep and shear their note with other users.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Vichhagar Nhin 0 Dec 24, 2021
PHP library to verify and validate Apple IdentityToken and authenticate a user with Apple ID.

Sign-in with Apple SDK Installation Recommended and easiest way to installing library is through Composer. composer require azimolabs/apple-sign-in-ph

Azimo Labs 79 Nov 8, 2022
This package helps you to associate users with permissions and permission groups with laravel framework

Laravel ACL This package allows you to manage user permissions and groups in a database, and is compatible with Laravel v5.8 or higher. Please check t

Mateus Junges 537 Dec 28, 2022
Laravel Users (Roles & Permissions, Devices, Password Hashing, Password History).

LARAVEL USERS Roles & Permissions Devices Password Hashing Password History Documentation You can find the detailed documentation here in Laravel User

Pharaonic 8 Dec 14, 2022
Laravel package to easily login as other users during development.

A Laravel 5.4 utility package to enable developers to log in as other users during development. Installation To install the package, simply follow the

VIA Creative 555 Jan 8, 2023
PermissionsMakr is a Laravel package that will help any developer to easily manage the system's users permissions

PermissionsMakr is a Laravel package that will help any developer to easily manage the system's users permissions

Alvarium Digital 3 Nov 30, 2021