Alagusundaram R
Alagusundaram R

Reputation: 7

How to reset keycloak admin password

import kcAdminClient from '../components/keycloak_clients.mjs';
import { Issuer } from 'openid-client';
import dotenv from 'dotenv'
dotenv.config()
  1. like this I import keycloak. here below is the error. node:internal/process/promises:288 triggerUncaughtException(err, true /* fromPromise */); ^ [UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "AxiosError: Request failed with status code 401".] { code: 'ERR_UNHANDLED_REJECTION' }

------------------------------------------------------------------------2. I find that admin password set in env is wrong. How to rest keycloak admin password. Actually I installed keycloak in windows

Upvotes: 0

Views: 1812

Answers (1)

Bench Vue
Bench Vue

Reputation: 9390

You can reset master admin's password by REST API

PUT /admin/realms/master/users/{admin user id}/reset-password

Body of JSON input

{
    "temporary": false,
    "type": "password",
    "value": "New password"
}

Demo

Old password is "admin"

New password is "1234"

launch Keycloak v24.2

Run by docker-compose in here

Save as demo.js

const axios = require('axios')
const querystring = require('querystring')

const getToken = async (password) => {
    try {
        const requestObject= querystring.stringify({
            grant_type: "client_credentials",
            client_id: "admin-cli",
            username: "admin",
            password: password,
            grant_type: "password"
        })
        const config = {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              "Accept":"*/*",
            }
        }
        const resp = await axios({
            method: 'POST',
            url:'http://localhost:8080/realms/master/protocol/openid-connect/token',
            data: requestObject,
            headers: config.headers})

        return Promise.resolve(resp.data.access_token)
    } catch (error) {
        return Promise.reject(error)
    }
}

const getUserId = async (master_token, user_name) => {
    try {
        const siteUrl = `http://localhost:8080/admin/realms/master/users/?username=${user_name}`
        const response = await axios.get(siteUrl, {
            headers: {
                'Accept-Encoding': 'application/json',
                Authorization: `Bearer ${master_token}`
            }
        });
        return Promise.resolve(response.data[0].id)

    } catch (error) {
        return Promise.reject(error)
    }
}

const resetPassword = async (master_token, user_id, new_password) => {
    try {
        const url = `http://localhost:8080/admin/realms/master/users/${user_id}/reset-password`
        const body = {
            temporary: false,
            type: "password",
            value: new_password
        }
        const config = {
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${master_token}`
            }
        }
        await axios.put(url, body, config)
        console.log(`Password for user ID ${user_id} reset successfully`)
    } catch (error) {
        console.error(`Error resetting password for user ID ${user_id}: ${error}`)
        throw error
    }
}

(async () => {
    const old_password = 'admin'
    const master_token = await getToken(old_password)
    console.log('master_token: ' + JSON.stringify(master_token))
    const user_name = 'admin'
    const user_id = await getUserId(master_token, user_name)
    console.log(user_name +'\'s ' + 'user_id: ' + user_id)
    
    const new_password = '1234' // Define your new password here
    await resetPassword(master_token, user_id, new_password)
})()

Install dependencies

npm install axios querystring

Run it

node demo.js

Result

New password is changed without error.

enter image description here

Upvotes: 1

Related Questions