设置后登录出现错误错误请求,需要在 keycloak 中使用值更新密码进行操作

问题描述 投票:0回答:1

我使用下面的代码创建了一个用户,然后使用API登录,响应返回错误请求!我如何才能捕获类似以下内容的响应:用户有巨大的要求操作,其值更新通行证?

感谢您的任何想法!

{       
    "username": "user",
    "email": "[email protected]",
    "enabled": true,             
    "credentials": [
        {
            "temporary": true,
            "type": "password",
            "value": "123"
        }
    ],
    "requiredActions": [
           "UPDATE_PASSWORD"
    ]
}
node.js rest keycloak bad-request keycloak-rest-api
1个回答
0
投票

您需要为

create user
reset password

分别调用 API

创建用户

POST /admin/realms/{realm}/users

身体

{
  "username": "user name",
  "email": "user email",
  "firstName": "first name",
  "lastName": "last name",
  "enabled": true,
  "emailVerified": true
}

重置密码

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

JSON 数据主体

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

演示

另存为

demo.js

const axios = require('axios');
const qs = require('qs');

const client_id = 'admin-cli';
const user_name = 'admin';
const pass_word = 'admin';
const grant_type = 'password';
const keycloakUrl = 'http://localhost:8080';
const tokenURL = `${keycloakUrl}/realms/master/protocol/openid-connect/token`;
const my_realm = 'my-realm';
const usersEndpoint = `${keycloakUrl}/admin/realms/${my_realm}/users`;

async function getTokenMaster() {
    const data = qs.stringify({
        client_id: client_id,
        username: user_name,
        password: pass_word,
        grant_type: grant_type
    });

    const config = {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    };

    try {
        const response = await axios.post(tokenURL, data, config);
        return response.data.access_token;
    } catch (error) {
        console.error('Error fetching token:', error);
        throw error;
    }
}

async function createUserInKeycloak(user, token) {
    try {
        await axios.post(usersEndpoint, {
            username: user.username,
            email: user.email,
            firstName: user.firstName,
            lastName: user.lastName,
            enabled: true,
            emailVerified: true
        }, {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });
        console.log(`User created: ${user.username}`);
    } catch (error) {
        console.error(`Error creating user ${user.username}:`, error);
    }
}
async function setPassword(userId, newPassword, token) {
    try {
        const url = `${keycloakUrl}/admin/realms/${my_realm}/users/${userId}/reset-password`;
        const response = await axios.put(url, {
            temporary: false,
            type: 'password',
            value: newPassword
        }, {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 204) {
            console.log(`Password successfully reset for user ID: ${userId}`);
        } else {
            console.log(`Received unexpected status code: ${response.status}`);
        }
    } catch (error) {
        console.error(`Error resetting password for user ID ${userId}:`, error);
        throw error; // or handle it as needed
    }
}

async function findUserId(username, token) {
    try {
        const url = `${keycloakUrl}/admin/realms/${my_realm}/users/?username=${username}`;
        const response = await axios.get(url, {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

        const users = response.data;
        if (users && users.length > 0) {
            // Assuming the username is unique and the first result is the desired user
            return users[0].id;
        } else {
            console.log(`User not found: ${username}`);
            return null;
        }
    } catch (error) {
        console.error(`Error finding user ${username}:`, error);
        throw error; // or handle it as needed
    }
}

async function main() {
    try {
        const token = await getTokenMaster();
        // create users
        const user = {
            username: 'user',
            password: '123',
            firstName: 'first',
            lastName: 'last',
            email: '[email protected]'
        }
        await createUserInKeycloak(user, token);
        const userId = await findUserId(user.username, token)
        console.log(`${user.username} ID: ${userId}, password: ${user.password}`);
        await setPassword(userId, user.password, token)

    } catch (error) {
        console.error('An error occurred:', error);
    }
}

main();

安装依赖项

npm install axios qs

运行它

node demo.js

结果

登录

作者:

UI

作者:

Postman

POST http://localhost:8080/realms/my-realm/protocol/openid-connect/token

身体有

x-www-form-urlencoded

grant_type: password
username: user
password: 123
client_id: admin-cli

作者:

cURL

curl --location 'http://localhost:8080/realms/my-realm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'username=user' \
--data-urlencode 'password=123' \
--data-urlencode 'client_id=admin-cli'

© www.soinside.com 2019 - 2024. All rights reserved.