Keycloak Login Error: expired_code & Non-Secure Cookie Context

Issue Overview

When using Keycloak, you may encounter the following log warnings related to authentication errors and non-secure cookies:

Example Logs:


2025-01-27 01:51:15,045 WARN  [org.keycloak.cookie.DefaultCookieProvider] (executor-thread-3) Non-secure context detected; cookies are not secured, and will not be available in cross-origin POST requests
2025-01-27 01:51:15,049 WARN  [org.keycloak.events] (executor-thread-3) type="LOGIN_ERROR", realmId="9821b5e9-f662-4cc9-bc87-19019604c1a8", realmName="master", clientId="security-admin-console", userId="null", ipAddress="172.16.1.234", error="expired_code", restart_after_timeout="true"

Causes:

  1. Expired Authentication Code:

    • The error expired_code suggests that the authentication code has expired. This can occur due to session timeouts, clock misalignment, or prolonged inactivity.
  2. Non-Secure Cookie Context:

    • The warning Non-secure context detected; cookies are not secured indicates that Keycloak is not using secure cookies (i.e., cookies are not sent over HTTPS). This can affect cross-origin POST requests and the availability of cookies.

Solutions

1. Clear Cache:

2. Ensure Secure Cookies:

3. Adjust Token Expiry or Session Timeout:

4. Time Synchronization:

5. Restart Keycloak:

Additional Notes

Example Keycloak Configuration Adjustments:

Secure Cookies:

To enforce secure cookies in Keycloak, update the configuration as follows:

<security-constraints>
    <cookie>
        <secure>true</secure>
        <http-only>true</http-only>
    </cookie>
</security-constraints>

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

Written by A.M. Rinas