每当我尝试将用户与组织关联时,它都会返回“用户不存在”,即使它存在(在数据库中)并且使用 get。
private async Task<bool> AddUserToOrganization(string organizationId, string userId)
{
string adminToken = await GetAdminTokenAsync();
if (string.IsNullOrEmpty(adminToken))
{
throw new Exception("Failed to fetch admin token.");
}
// Set the authorization header
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", adminToken);
var orgUrl = $"{_configuration["Keycloak:BaseUrl"]}/admin/realms/{_configuration["Keycloak:Realm"]}/organizations/{organizationId}/members";
var requestBody = new { userId = userId }; // Create the HTTP request
var request = new HttpRequestMessage(HttpMethod.Post, orgUrl) { Content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json") }; // Send the request
var orgResponse = await _httpClient.SendAsync(request);
if (!orgResponse.IsSuccessStatusCode)
{
var errorResponse = await orgResponse.Content.ReadAsStringAsync();
// Step 3: Perform cleanup
await CleanupFailedOperationAsync(organizationId, userId);
throw new Exception($"Failed to add user to organization. Status: {orgResponse.StatusCode}, Response: {errorResponse}");
}
return true;
}
我尝试将请求正文更改为:
{
string[] requestBody= new[] { userId};
string[] requestBody= [userId];
string requestBody= userId;
var requestBody = new {userId=userId};
List<string> requestBody = new {userId};
}
我正在将 keycloak v.26.0.7 与 postgresql 和 docker 一起使用。任何帮助将不胜感激。
您可以简单地通过说 userId 是请求正文来回答问题,而不是否决这个问题(我认为我已经尝试过)。所以答案是:
private async Task<bool> AddUserToOrganization(string organizationId, string userId)
{
string adminToken = await GetAdminTokenAsync();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", adminToken);
var url = $"{_configuration["Keycloak:BaseUrl"]}/admin/realms/{_configuration["Keycloak:Realm"]}/organizations/{organizationId}/members";
var requestContent = new StringContent(JsonSerializer.Serialize(userId), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(url, requestContent);
if (!response.IsSuccessStatusCode)
{
var errorResponse = await response.Content.ReadAsStringAsync();
throw new Exception($"Failed to add user to organization. Status: {response.StatusCode}, Response: {errorResponse}");
}
return true;
}