nodejs-keycloak
v1.0.5
Published
`nodejs-keycloak` is a Node.js package for communicating with a Keycloak server. It allows you to verify JWT tokens generated by Keycloak and, if provided with a username and password, perform various Keycloak API operations such as obtaining access token
Downloads
14
Readme
nodejs-keycloak
nodejs-keycloak
is a Node.js package for communicating with a Keycloak server. It allows you to verify JWT tokens generated by Keycloak and, if provided with a username and password, perform various Keycloak API operations such as obtaining access tokens, refresh tokens, or creating new realms.
Installation
You can install the package via npm:
npm install nodejs-keycloak
Usage
Importing the Package
First, import the package and get the Keycloak class:
const { KeycloakClient } = require("nodejs-keycloak");
Initializing the Keycloak Instance
Create an instance of the Keycloak class by providing the Keycloak server URL and realm name. Optionally, you can provide a username and password.
const keycloak = new KeycloakClient({
serverUrl: "http://localhost:8080",
realm: "your-realm",
client_id: "web-client",
username: "your-username", // optional
password: "your-password", // optional
});
Verifying JWT Tokens
Once the Keycloak instance is ready, you can use it to verify JWT tokens generated by the Keycloak server:
const token = "my-jwt-token";
keycloak
.verifyJwt(token)
.then((decoded) => {
console.log(decoded);
})
.catch((error) => {
console.log(error);
});
Or
const token = "my-jwt-token";
try{
const decoded = await keycloak.verifyJwt(token)
console.log(decoded)
}
catch(error){
console.log(error)
}
Keycloak API Operations
If the username and password are provided, you can use the same instance to call Keycloak APIs.
Get Access Token
keycloak
.getAccessToken()
.then((token) => {
console.log(token);
})
.catch((error) => {
console.log(error);
});
Or
try{
const token = await keycloak.getAccessToken()
console.log(token)
}
catch(error){
console.log(error)
}
Get Refresh Token
keycloak
.getRefreshToken()
.then((token) => {
console.log(token);
})
.catch((error) => {
console.log(error);
});
Or
try{
const token = await keycloak.getRefreshToken()
console.log(token)
}
catch(error){
console.log(error)
}