Download the PHP package dmstr/yii2-usuario-keycloak without Composer
On this page you can find all versions of the php package dmstr/yii2-usuario-keycloak. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package yii2-usuario-keycloak
Yii2 usuario keycloak client
Installation
Install the package via composer
For the installation of usuario see usuario docs
Setup
To run a keycloak using Docker (compose) please see docker-compose.keycloak.yml in the docker folder
For local development you should add keycloak-local to your /etc/hosts like this: 127.0.0.1 keycloak-local
You may need to replace 127.0.0.1 with your docker ip
Configuration
This part of config is mandatory. With this we add keycloak as a "social network"
Enable front channel logout from keycloak when user logs out in app
Social login mode (SSO connect hardening)
When a Keycloak login callback arrives while a local session already exists, the base
2amigos/yii2-usuario behaviour treats it as "connect the returned identity to the current
session". That is correct for classic interactive account-linking (a logged-in user clicks
"connect Google" in their profile), but wrong for pure SSO deployments where the same
security/auth endpoint is the primary login: a stale session then captures whatever identity
the callback returns — binding the wrong person's Keycloak sub to the open account.
SecurityController::$socialLoginMode controls this. The default is legacy so existing
installations are unaffected; SSO deployments should opt in to guarded.
| Mode | Guest login | Login while a session is open | Use for |
|---|---|---|---|
legacy (default) |
authenticate | connect returned identity to the open session (no identity check) | non-SSO / classic account-linking; backwards-compatible default |
guarded (recommended for SSO) |
authenticate | connect only if the returned identity provably belongs to the same user (owner resolved by immutable sub, else by verified e-mail); otherwise log out the stale session and authenticate as the true identity |
pure Keycloak SSO where the auth endpoint is the primary login |
authenticate |
authenticate | always authenticate via the token identity; never connect-to-session | SSO where profile-based account-linking is never used |
Notes:
- Unknown values fail fast. An invalid
socialLoginMode(e.g. a typo) throwsInvalidConfigExceptionininit()— it never silently falls back tolegacy, so a consumer that meant to opt in to hardening cannot end up unprotected by accident. email_verifiedis enforced strictly inguarded: a missingemail_verifiedclaim counts as not verified. This is deliberately stricter than the app-side event handler pattern below (isset(...) && === false, which lets a missing claim through).guardedpopulatesemail/usernameon the account row (unlike the base connect path), so it produces no new rows with empty columns.- Pre-existing mislinks are perpetuated, not repaired. Under
guardedthe owner is resolved from the current DB state, so an already-wrongsub → userlink keeps logging in the wrong user until the data is cleaned. Deploy the code fix first, then run the data cleanup. guardedcannot tell an SSO login from an intentional profile connect, because both run through the samesecurity/authendpoint. If a deployment relies on users deliberately linking a second identity with a different verified e-mail,guardedwill block that. Evaluate before enabling.- Planned change: the default is expected to flip to
guardedin 6.0.0.
Only allow login to users with verified emails
Disabled the sending of a welcome message when a user is from keycloak
If you do not want to allow identity switching. This is recommended because potential RBAC Roles with the TokenRoleRule may not work correctly
Logout the user if the keycloak token is expired
This only works in a web application so add your config accordingl and needs some slight modifications to your user component. You can copy and use this example or extend your existing user compoent.
Change the login url so the site redirect you directly to the keycloak login page
User identity to use in rest calls
We suggest to use the JwtHttpBearerAuth from bizley/yii2jwt for this. You can
use the following example to implement it in your user
Using the identity class
Generate the keys for the jwt
if you only want to use validation and parsing you can configure the jwt component like this.
In combination with a Keycloak, the value KEYCLOAK_PUBLIC_KEY_FILE should be that from the Keycloak Public Key
When using the JwtHttpBearerAuth ensure that cors is before the authenticator in the behaviors of your controller
or module and all access controll stuff is after.
Auto submit social account registration confirm form
Add a JWT Component to be able to parse JWT Tokens
TokenRoleRule
This rule allows you to assign roles to users based on the roles they have in keycloak. This is useful if you want to use keycloak as a single source of truth for your user roles. Note that the role names in keycloak must match the roles in RBAC and should be assigned to the "Default" Role so they get evaluated for all logged in users.
The TokenRoleRule Rule can be configured to work with different Keycloak configurations.
Default configuration:
$authClientId$
is the name of the client in the main.php used to connect to an IDP. It defaults to 'keycloak'
$rbacRolesClaimName$
claim where the Roles are saved in the Access Token. Keycloak defaults to 'realm_access.roles'
$jwtComponent$
JWT component used to parse JWT Tokens. Defaults to 'jwt'
$authCollectionComponent$
Auth collection of clients. Defaults to 'authClientCollection'
$tokenParam$
Parameter used to extract the Token used for role checking, defaults to 'access_token'
Configuration
The parameters mentioned above can be configured like this
JwtAutoProvisionAuth
JwtAutoProvisionAuth is an authentication filter that automatically creates user accounts when someone logs in with a valid JWT token from auth client. If a user with the token's email doesn't exist in the
system, it creates a new user account and links it to the Keycloak identity; if the user already exists, it just connects the auth client account to the existing user. This allows seamless user onboarding
where people can access the application immediately using their auth client credentials without manual account creation.
It is auto configured to use a jwt component named jwt and a auth client named keycloak
Example usage in a yii\rest\Controller or yii\base\Module
Front Channel Logout
For this to work you must use a yii\web\MultiFieldSession session e.g. yii\web\DbSession
Web config for extra fields write callback in session
Console config for migrations if you use yii\web\DbSession
Optional but recommended: If you use codemix\localeurls\UrlManager as an url manager add this to you web config prevent unnecassary redirects
In your keycloak add this as your front channel logout url in the client settings: https://your-domain/user/security/front-channel-logout
Custom IDP Hint
Used to automatically redirect to an existent Broker. Current default in SecurityController is set to the Keycloak default kc_idp_hint.
To set a custom param overwrite idp_hint_param in SecurityController.
To use this feature, add the hint to the URL after the authclient
All versions of yii2-usuario-keycloak with dependencies
2amigos/yii2-usuario Version ^1.6.3
web-token/jwt-signature-algorithm-hmac Version ^3.2
web-token/jwt-signature-algorithm-ecdsa Version ^3.2
web-token/jwt-signature-algorithm-rsa Version ^3.2
web-token/jwt-checker Version ^3.2
web-token/jwt-key-mgmt Version ^3.2
web-token/jwt-library Version ^3.4
lcobucci/jwt Version ^5.1