我使用 keycloak-js 来检查加载时的 sso。问题是,当服务器关闭或发生其他情况时,浏览器(Web 视图)会重定向到“无法访问此站点。ERR_CONNECTION_TIMED_OUT”屏幕/页面。
如何防止 keycloak-js 在 sso 服务器不可用(连接超时)时重定向。
await keycloak.init({
checkLoginIframe: false,
flow: 'standard',
onLoad: 'check-sso',
});
我看到了
keycloak.onAuthError
,但是如何做类似preventDefault
的事情呢?导航到离线页面?我只想捕获这个并手动显示错误而不重定向。
您似乎想在没有 Keycloak 提供的自动重定向行为的情况下优雅地处理身份验证错误。为了实现这一点,您确实可以利用 Keycloak 提供的 onAuthError 事件。但是,正如您所提到的,没有像典型事件处理场景那样的内置 PreventDefault 方法。相反,您可以实现自己的逻辑来处理错误而无需重定向。
您可以采取以下方法:
// Initialize Keycloak
const keycloak = Keycloak();
// Set up event listener for authentication errors
keycloak.onAuthError = function(errorData) {
// Handle the authentication error here
console.error("Authentication Error:", errorData);
// Optionally, you can display an error message to the user
showError("Authentication error occurred. Please try again later.");
// Optionally, you can log the user out or take other actions based on your application's requirements
// keycloak.logout();
};
// Initialize Keycloak with options
keycloak.init({
checkLoginIframe: false,
flow: 'standard',
onLoad: 'check-sso',
}).then((authenticated) => {
if (authenticated) {
// User is authenticated
console.log("User is authenticated");
} else {
// User is not authenticated
console.log("User is not authenticated");
}
}).catch((error) => {
// Handle initialization errors
console.error("Initialization Error:", error);
// Optionally, display an error message to the user
showError("Initialization error occurred. Please try again later.");
});
在此示例中:
确保将 showError 替换为您自己的函数,以向用户显示错误消息或执行任何其他必要的操作。这样,您就可以优雅地处理身份验证错误,而无需自动重定向。