我正在尝试在页面加载时访问 Keycloak 服务器,以便用户可以在那里进行身份验证并获取令牌。当我向 Keycloak 提供所有信息时,我收到错误:
Refused to frame Keycloak URL because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self'".
以下是我使用 Nuxt 3 或 Vuejs 3 应用程序的代码:
可组合项/fetchToken.js:
import Keycloak from 'keycloak-js';
const config = useRuntimeConfig();
export default async function fetchToken() {
console.log("WITHIN FETCH");
const initOptions = useState("initOptions", () => ({
realm: config.public.KEYCLOAK_REALM_NAME,
clientId: config.public.KEYCLOAK_CLIENT_ID,
url: config.public.KEYCLOAK_SERVER_URL
}));
console.log(JSON.stringify(initOptions.value,null,4))
// Create a new instance of the Keycloak constructor
const keycloak = new Keycloak(initOptions.value);
console.log(keycloak)
console.log(JSON.stringify(keycloak,null,4))
try {
// Initialize Keycloak and handle the authentication
const auth = await keycloak.init({ onLoad: 'login-required' });
console.log('Token:', keycloak.token);
if (!auth) {
window.location.reload();
} else {
console.log('Authenticated');
}
if (keycloak.token) {
window.localStorage.setItem('keycloakToken', keycloak.token);
}
//redirect to the home page after login
await router.push('/');
} catch (error) {
console.error('Error initializing Keycloak:', error);
}
}
我在以下页面中使用它: 页面/index.vue:
<template>
</template>
<script setup>
//Execute the onBeforeMount to redirect to Keycloak Login
onBeforeMount(() => {
fetchToken();
});
</script>
如何解决 Keycloak 中的问题并在重新加载页面时获取身份验证和令牌?
提供答案,因为它可能对将来的某人有用。我使用 Vue 3 应用程序使用 keycloak js 从 keycloak 获取令牌,并从 keycloak 注销用户。
我相信使用以下内容很重要,如果不是,请检查 Keycloak UI 中的 keycloak 配置。
// Initialize Keycloak and handle the authentication
const auth = await keycloak.init({
onLoad: "login-required",
flow: "implicit",
});
我使用以下方法使用 keycloak js 从我的 keycloak 中获取令牌:
我的环境文件:
KEYCLOAK_SERVER_URL=http://localhost:9080
KEYCLOAK_LOGOUT_URL=http://localhost:9080/realms/myRealmName/protocol/openid-connect/logout
API_SERVER_URL=http://localhost:8080/
以下是我的可组合文件,用于获取令牌并存储它:
import Keycloak from "keycloak-js";
const config = useRuntimeConfig();
const initOptions = useState("initOptions", () => ({
realm: config.public.KEYCLOAK_REALM_NAME,
clientId: config.public.KEYCLOAK_CLIENT_ID,
url: config.public.KEYCLOAK_SERVER_URL,
}));
// Create a new instance of the Keycloak constructor
const keycloak = new Keycloak(initOptions.value);
//Function to login to Keycloak and generate token and ID token
export async function keycloakLogin() {
try {
// Initialize Keycloak and handle the authentication
const auth = await keycloak.init({
onLoad: "login-required",
flow: "implicit",
});
//If not authenticated then reload to show login page
if (!auth) {
window.location.reload();
}
//If token is present then store it in localstorage
if (keycloak.token) {
console.log(keycloak.token);
console.log(keycloak.idToken);
window.localStorage.setItem("keycloakToken", keycloak.token);
window.localStorage.setItem("idToken", keycloak.idToken);
}
// Call the setupTokenChecking function to initiate token checking
setupTokenChecking();
} catch (error) {
console.error("Error initializing Keycloak:", error);
}
}
//Function to logout the user if the user has clicked logout button
export async function keycloakLogout() {
const logoutURL =
config.public.KEYCLOAK_LOGOUT_URL +
"?id_token_hint=" +
localStorage.getItem("idToken") +
"&post_logout_redirect_uri=" +
encodeURIComponent(window.location.href);
keycloak
.logout({ redirectUri: logoutURL })
.then((success) => {
console.log("User logout success ", success);
})
.catch((error) => {
console.log("User logout error ", error);
});
}
// Call the checkAndRenewToken function initially and set up periodic checks
async function setupTokenChecking() {
await checkAndRenewToken(); // Check the token immediately upon setup
const tokenCheckInterval = 5 * 60 * 1000; // periodic token checks for 5 minutes in milliseconds
setInterval(checkAndRenewToken, tokenCheckInterval);
}
// Function to periodically check and renew the Keycloak token
export async function checkAndRenewToken() {
try {
if (keycloak.isTokenExpired()) {
console.log("Token is expired. Renewing token...");
try {
await keycloak.updateToken(60);
} catch (error) {
console.error(
"Refresh Token Failed : " + JSON.stringify(error, null, 4)
);
window.location.reload();
}
}
} catch (error) {
console.error("Error checking/renewing token:", error);
}
}