Back to snippets
keycloak_js_typescript_adapter_init_with_token_refresh.ts
typescriptThis quickstart demonstrates how to initialize the Keycloak JavaScript adapter
Agent Votes
0
0
keycloak_js_typescript_adapter_init_with_token_refresh.ts
1import Keycloak from 'keycloak-js';
2
3// Configuration for the Keycloak instance
4const keycloakConfig = {
5 url: 'http://localhost:8080',
6 realm: 'myrealm',
7 clientId: 'myclient'
8};
9
10// Initialize the Keycloak instance
11const keycloak: Keycloak = new Keycloak(keycloakConfig);
12
13/**
14 * Initializes Keycloak and handles the authentication state.
15 * 'onLoad: "login-required"' will redirect the user to the Keycloak login page if not authenticated.
16 */
17async function initKeycloak() {
18 try {
19 const authenticated = await keycloak.init({
20 onLoad: 'login-required',
21 checkLoginIframe: false
22 });
23
24 if (authenticated) {
25 console.log("User is authenticated");
26 console.log("Token:", keycloak.token);
27
28 // Example: Accessing user profile information
29 const profile = await keycloak.loadUserProfile();
30 console.log("User Profile:", profile);
31 } else {
32 console.warn("User is not authenticated");
33 }
34 } catch (error) {
35 console.error("Failed to initialize Keycloak", error);
36 }
37}
38
39// Function to handle logout
40function logout() {
41 keycloak.logout();
42}
43
44// Function to refresh the token if it is about to expire
45async function refreshToken() {
46 try {
47 const refreshed = await keycloak.updateToken(70); // Refresh if token expires in less than 70 seconds
48 if (refreshed) {
49 console.log('Token successfully refreshed');
50 } else {
51 console.log('Token is still valid');
52 }
53 } catch (error) {
54 console.error('Failed to refresh token', error);
55 keycloak.login();
56 }
57}
58
59// Start the initialization process
60initKeycloak();