Users authenticate with Keycloak rather than individual applications. This means that your applications don't have to deal with login forms, authenticating users, and storing users. Once logged-in to Keycloak, users don't have to login again to access a different application.
This also applies to logout. Keycloak provides single-sign out, which means users only have to logout once to be logged-out of all applications that use Keycloak.
Enabling login with social networks is easy to add through the admin console. It's just a matter of selecting the social network you want to add. No code or changes to your application is required.
Keycloak can also authenticate users with existing OpenID Connect or SAML 2.0 Identity Providers. Again, this is just a matter of configuring the Identity Provider through the admin console.
Keycloak has built-in support to connect to existing LDAP or Active Directory servers. You can also implement your own provider if you have users in other stores, such as a relational database.
Through the admin console administrators can centrally manage all aspects of the Keycloak server.
They can enable and disable various features. They can configure identity brokering and user federation.
They can create and manage applications and services, and define fine-grained authorization policies.
They can also manage users, including permissions and sessions.
Through the account management console users can manage their own accounts. They can update the profile, change passwords, and setup two-factor authentication
Users can also manage sessions as well as view history for the account.
If you've enabled social login or identity brokering users can also link their accounts with additional providers to allow them to authenticate to the same account with different identity providers.
Keycloak is based on standard protocols and provides support for OpenID Connect, OAuth 2.0, and SAML.
If role based authorization doesn't cover your needs, Keycloak provides fine-grained authorization services as well. This allows you to manage permissions for all your services from the Keycloak admin console and gives you the power to define exactly the policies you need.
As mentioned previously, policies define the conditions that must be satisfied before granting access to an object.
Procedure
1. Click the Policy tab to view all policies associated with a resource server.
Policies
Keycloak supports fine-grained authorization policies and is able to combine different access control mechanisms such as:
Keycloak is based on a set of administrative UIs and a RESTful API, and provides the necessary means to create permissions for your protected resources and scopes, associate those permissions with authorization policies, and enforce authorization decisions in your applications and services.
Resource servers (applications or services serving protected resources) usually rely on some kind of information to decide if access should be granted to a protected resource. For RESTful-based resource servers, that information is usually obtained from a security token, usually sent as a bearer token on every request to the server. For web applications that rely on a session to authenticate users, that information is usually stored in a user’s session and retrieved from there for each request.
The first step to enable Keycloak Authorization Services is to create the client application that you want to turn into a resource server.
Procedure
1. Click Clients.
Clients
HashAlgorithm
Passwords are not stored in cleartext. Before storage or validation, Keycloak hashes passwords using standard hashing algorithms. PBKDF2 is the only built-in and default algorithm available. See the Server Developer Guide on how to add your own hashing algorithm.
Hashing iterations
Specifies the number of times Keycloak hashes passwords before storage or
verification. The default value is 27,500.
Keycloak hashes passwords to ensure that hostile actors with access to the password
database cannot read passwords through reverse engineering.
Digits
The number of numerical digits required in the password string.
Lowercase characters
The number of lower case letters required in the password string.
Uppercase characters
The number of upper case letters required in the password string.
Special characters
The number of special characters required in the password string.
Not username
The password cannot be the same as the email address of the user.
Regular expression
Password must match one or more defined regular expression patterns.
Expire password
The number of days the password is valid. When the number of days has expired,
the user must change their password.
Not recently used
Password cannot be already used by the user. Keycloak stores a history of used
passwords. The number of old passwords stored is configurable in Keycloak.
Password blacklist
Password must not be in a blacklist file.
You can use this type of policy to define time conditions for your permissions.
To create a new time-based policy, select Time in the item list in the upper right corner of the policy listing.
Add Time Policy
As an alternative to logging to the console, you can use unstructured logging to a file.
Logging to a file is disabled by default. To enable it, enter the following command:
bin/kc.[sh|bat] start --log="console,file"
A log file named keycloak.log is created inside the data/log directory of your Keycloak installation.
To change where the log file is created and the file name, perform these steps:
1. Create a writable directory to store the log file.If the directory is not writable, Keycloak will start correctly, but it will issue an error and no log file will be created.
2. Enter this command:
bin/kc.[sh|bat] start --log="console,file"
--log-file=
Keycloak is a single sign on solution for web apps and RESTful web services. The goal of Keycloak is to make security simple so that it is easy for application developers to secure the apps and services they have deployed in their organization. Security features that developers normally have to write for themselves are provided out of the box and are easily tailorable to the individual requirements of your organization. Keycloak provides customizable user interfaces for login, registration, administration, and account management. You can also use Keycloak as an integration platform to hook it into existing LDAP and Active Directory servers. You can also delegate authentication to third party identity providers like Facebook and Google.
Keycloak provides the following features:
Keycloak is based on a set of administrative UIs and a RESTful API, and provides the necessary means to create permissions for your protected resources and scopes, associate those permissions with authorization policies, and enforce authorization decisions in your applications and services.
Resource servers (applications or services serving protected resources) usually rely on some kind of information to decide if access should be granted to a protected resource. For RESTful-based resource servers, that information is usually obtained from a security token, usually sent as a bearer token on every request to the server. For web applications that rely on a session to authenticate users, that information is usually stored in a user’s session and retrieved from there for each request.
Frequently, resource servers only perform authorization decisions based on role-based access control (RBAC), where the roles granted to the user trying to access protected resources are checked against the roles mapped to these same resources. While roles are very useful and used by applications, they also have a few limitations:
Considering that today we need to consider heterogeneous environments where users are distributed across different regions, with different local policies, using different devices, and with a high demand for information sharing, Keycloak Authorization Services can help you improve the authorization capabilities of your applications and services by providing:
curl -X POST \ -H "Content-Type: application/x-www-form-urlencoded" \ -d 'grant_type=client_credentials&client_id=${client_id}&client_secret=${client_secret}' \ "http://localhost:8080/realms/${realm_name}/protocol/openid-connect/token"
The example above is using the client_credentials grant type to obtain a PAT from the server. As a result, the server returns a response similar to the following:
{ "access_token": ${PAT}, "expires_in": 300, "refresh_expires_in": 1800, "refresh_token": ${refresh_token}, "token_type": "bearer", "id_token": ${id_token}, "not-before-policy": 0, "session_state": "ccea4a55-9aec-4024-b11c-44f6f168439e" }
Resource servers can manage their resources remotely using a UMA-compliant endpoint.
http://${host}:${port}/realms/${realm_name}/authz/protection/resource_set
This endpoint provides operations outlined as follows (entire path omitted for clarity):
The claims parameter is specified in a JSON representation:
claims= { "id_token": { "acr": { "essential": true, "values": ["gold"] } } }
The Keycloak javascript adapter has support for easy construct of this JSON and sending it in the login request. See Javascript adapter documentation for more details.
You can also use simpler parameter acr_values instead of claims parameter to request particular levels as non-essential. This is mentioned in the OIDC specification.
You can also configure the default level for the particular client, which is used when the parameter acr_values or the parameter claims with the acr claim is not present. For further details, see Client ACR configuration.
For more details see the official OIDC specification.
The logic for the previous configured authentication flow is as follows: If a client request a high authentication level, meaning Level of Authentication 2 (LoA 2), a user has to perform full 2-factor authentication: Username/Password + OTP. However, if a user already has a session in Keycloak, that was logged in with username and password (LoA 1), the user is only asked for the second authentication factor (OTP).
The option Max Age in the condition determines how long (how much seconds) the subsequent authentication level is valid. This setting helps to decide whether the user will be asked to present the authentication factor again during a subsequent authentication. If the particular level X is requested by the claims or acr_values parameter and user already authenticated with level X, but it is expired (for example max age is configured to 300 and user authenticated before 310 seconds) then the user will be asked to re-authenticate again with the particular level. However if the level is not yet expired, the user will be automatically considered as authenticated with that level.
Required field. Enter a URL pattern and click + to add and - to remove existing URLs and click Save. You can use wildcards at the end of the URL pattern. For example http://host.com/*
Exclusive redirect URL patterns are typically more secure. See Unspecific Redirect URIs for more information.
Enter a URL pattern and click + to add and - to remove existing URLs. Click Save.
This option handles Cross-Origin Resource Sharing (CORS). If browser JavaScript attempts an AJAX HTTP request to a server whose domain is different from the one that the JavaScript code came from, the request must use CORS. The server must handle CORS requests, otherwise the browser will not display or allow the request to be processed. This protocol protects against XSS, CSRF, and other JavaScript-based attacks.
Domain URLs listed here are embedded within the access token sent to the client application. The client application uses this information to decide whether to allow a CORS request to be invoked on it. Only Keycloak client adapters support this feature. See Securing Applications and Services Guide for more information.
Callback endpoint for a client. The server uses this URL to make callbacks like pushing revocation policies, performing backchannel logout, and other administrative operations. For Keycloak servlet adapters, this URL can be the root URL of the servlet application. For more information, see Securing Applications and Services Guide.
Capability Config
The type of OIDC client.
For server-side clients that perform browser logins and require client secrets when making an Access Token Request. This setting should be used for server-side applications
For client-side clients that perform browser logins. As it is not possible to ensure that secrets can be kept safe with client-side clients, it is important to restrict access by configuring correct redirect URIs.
Enables or disables fine-grained authorization support for this client.
If enabled, this client can use the OIDC Authorization Code Flow.
If enabled, this client can use the OIDC Direct Access Grants.
If enabled, this client can use the OIDC Implicit Flow.
If enabled, this client can authenticate to Keycloak and retrieve access token dedicated to this client. In terms of OAuth2 specification, this enables support of Client Credentials Grant for this client.
If enabled, this client can use the OIDC Direct Access Grants.
If enabled, this client can use the OIDC Device Authorization Grant.
If enabled, this client can use the OIDC Client Initiated Backchannel Authentication Grant.
Login settings
A theme to use for login, OTP, grant registration, and forgotten password pages.
If enabled, users have to consent to client access.
For client-side clients that perform browser logins. As it is not possible to ensure that secrets can be kept safe with client-side clients, it is important to restrict access by configuring correct redirect URIs.
This switch applies if Consent Required is Off.
The consent screen will contain only the consents corresponding to configured client scopes.
There will be also one item on the consent screen about this client itself.
Account events:
Each event has a corresponding error event.
Event listeners listen for events and perform actions based on that event. Keycloak includes two built-in listeners, the Logging Event Listener and Email Event Listener.
The logging event listener
When the Logging Event Listener is enabled, this listener writes to a log file when an error event occurs.
An example log message from a Logging Event Listener:
11:36:09,965 WARN [org.keycloak.events] (default task-51) type=LOGIN_ERROR, realmId=master, clientId=myapp, userId=19aeb848-96fc-44f6-b0a3-59a17570d374, ipAddress=127.0.0.1, error=invalid_user_credentials, auth_method=openid-connect, auth_type=code, redirect_uri=http://localhost:8180/myapp, code_id=b669da14-cdbb-41d0-b055-0810a0334607, username=admin
You can use the Logging Event Listener to protect against hacker bot attacks:
1. Parse the log file for the LOGIN_ERROR event.
2. Extract the IP Address of the failed login event.
3. Send the IP address to an intrusion prevention software framework tool.
The Logging Event Listener logs events to the org.keycloak.events log category. Keycloak does not include debug log events in server logs, by default.
To include debug log events in server logs:
1. Change the log level for the org.keycloak.events category
2. Change the log level used by the Logging Event listener.
To change the log level used by the Logging Event listener, add the following:
bin/kc.[sh|bat] start --spi-events-listener-jboss-logging-success-level=info --spi-events-listener-jboss-logging-error-level=error
The valid values for log levels are debug, info, warn, error, and fatal
The Email Event Listener
The Email Event Listener sends an email to the user’s account when an event occurs and supports the following events:
By default, new client applications have unlimited role scope mappings. Every access token for that client contains all permissions that the user has. If an attacker compromises the client and obtains the client’s access tokens, each system that the user can access is compromised.
Limit the roles of an access token by using the Scope menu for each client. Alternatively, you can set role scope mappings at the Client Scope level and assign Client Scopes to your client by using the Client Scope menu.
In environments with low levels of trust among services, limit the audiences on the token. See the OAuth2 Threat Model and the Audience Support section for more information.
When a login page is opened for the first time in a web browser, Keycloak creates an object called authentication session that stores some useful information about the request. Whenever a new login page is opened from a different tab in the same browser, Keycloak creates a new record called authentication sub-session that is stored within the authentication session. Authentication requests can come from any type of clients such as the Admin CLI. In that case, a new authentication session is also created with one authentication sub-session. Please note that authentication sessions can be created also in other ways than using a browser flow. The text below is applicable regardless of the source flow.
Use the update command on the events/config endpoint.
The eventsListeners attribute contains a list of EventListenerProviderFactory IDs,
specifying all event listeners that receive events. Attributes are available that
control built-in event storage, so you can query past events using the Admin REST
API. Keycloak has separate control over the logging of service calls (eventsEnabled)
and the auditing events triggered by the Admin Console or Admin REST API
(adminEventsEnabled). You can set up the eventsExpiration event to expire to prevent
your database from filling. Keycloak sets eventsExpiration to time-to-live expressed
in seconds.
You can set up a built-in event listener that receives all events and logs the
events through JBoss-logging. Using the org.keycloak.events logger, Keycloak logs
error events as WARN and other events as DEBUG.
For example:
$ kcadm.sh update events/config -r demorealm -s 'eventsListeners=["jboss-logging"]'
c:\> kcadm update events/config -r demorealm -s "eventsListeners=[\"jboss-logging\"]"
For example:
You can turn on storage for all available ERROR events, not including auditing events, for two days so you can retrieve the events through Admin REST.
You can turn on storage for all available ERROR events, not including auditing events, for two days so you can retrieve the events through Admin REST.
1. Set the realm’s passwordPolicy attribute to an enumeration expression that includes the specific policy provider ID and optional configuration.
2. Use the following example to set a password policy to default values. The default values include:
$ kcadm.sh update realms/demorealm -s 'passwordPolicy="hashIterations and specialChars and upperCase and digits and notUsername and length"'
3. To use values different from defaults, pass the configuration in brackets.
4. Use the following example to set a password policy to:
$ kcadm.sh update realms/demorealm -s 'passwordPolicy="hashIterations(25000) and specialChars(2) and upperCase(2) and lowerCase(2) and digits(2) and length(9) and notUsername and passwordHistory(4)"'
You can get the current realm configuration by filtering all output except for the passwordPolicy attribute.
For example, display passwordPolicy for demorealm.
$ kcadm.sh get realms/demorealm --fields passwordPolicy
Run the get command on the authentication/flows endpoint
For example:
$ kcadm.sh get authentication/flows -r demorealm
Run the get command on the authentication/flows/FLOW_ID endpoint.
For example:
$ kcadm.sh get authentication/flows/febfd772-e1a1-42fb-b8ae-00c0566fafb8 -r demorealm
Run the get command on the authentication/flows/FLOW_ALIAS/executions endpoint.
For example:
$ kcadm.sh get authentication/flows/Copy%20of%20browser/executions -r demorealm
Get execution for a flow.
Note the ID of the flow.
Run the create command on the authentication/executions/{executionId}/config endpoint.
For example:
$ kcadm create "authentication/executions/a3147129-c402-4760-86d9-3f2345e401c7/config" -r examplerealm -b '{"config":{"x509-cert-auth.mapping-source-selection":"Match SubjectDN using regular expression","x509-cert-auth.regular-expression":"(.*?)(?:$)","x509-cert-auth.mapper-selection":"Custom Attribute Mapper","x509-cert-auth.mapper-selection.user-attribute-name":"usercertificate","x509-cert-auth.crl-checking-enabled":"","x509-cert-auth.crldp-checking-enabled":false,"x509-cert-auth.crl-relative-path":"crl.pem","x509-cert-auth.ocsp-checking-enabled":"","x509-cert-auth.ocsp-responder-uri":"","x509-cert-auth.keyusage":"","x509-cert-auth.extendedkeyusage":"","x509-cert-auth.confirmation-page-disallowed":""},"alias":"my_otp_config"}'