gpt4 book ai didi

java - 使用 keycloak-admin-client 创建用户期间出现 403

转载 作者:行者123 更新时间:2023-12-02 09:19:01 24 4
gpt4 key购买 nike

我正在尝试使用 java-admin-client 创建一个新用户。我使用 keycloak UI 在我的领域创建了一个新客户端。

客户:

访问类型: secret

角色: View 用户、 View 领域、 View 客户端、管理用户(这些角色只是在 keycloak UI 中按名称添加)

代码:

final Keycloak keycloak = KeycloakBuilder.builder()
.serverUrl("https://{keycloakurl}/auth")
.realm(realm)
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.clientId("client")
.clientSecret("uuidSecret")
.build();

final UserRepresentation user = new UserRepresentation();
user.setEnabled(true);
user.setUsername("test");
user.setFirstName("test1");
user.setLastName("test2");
user.setEmail("test@test.com");
user.setAttributes(Collections.singletonMap("origin", Arrays.asList("demo")));

final RealmResource realmResource = keycloak.realm(realm);
final UsersResource userResource = realmResource.users();

final Response response = userResource.create(user);

最后一行给我 403 Forbidden。

最佳答案

我认为 403 因为您没有“管理用户”角色。在您的领域内从“领域管理”客户端添加到您的用户。

我们创建了一个服务帐户用户,只是为了通过 uuid 查询用户。这三个文件以及 application.properties 中的属性可以实现此目的。更新代码并尝试你想要的

@EnableOAuth2Client
@Configuration
public class KeycloakConfiguration {

// token-service-uri=https://keycloak.internal/auth/realms/some-realm/protocol/openid-connect/token
// admin-query.client-id=client
// admin-query.username=service-account
// admin-query.password=password
// admin-query.admin-base-url=https://keycloak.internal/auth/admin/realms/realm

@Value("${token-service-uri}")
private String tokenServiceUri;

@Value("${admin-query.client-id}")
private String clientId;

@Value("${keycloak.credentials.secret}")
private String clientSecret;

@Value("${admin-query.username}")
private String username;

@Value("${admin-query.password}")
private String password;


private final String grantType = "password";


@Bean
public OAuth2ProtectedResourceDetails cryptoKeycloakResourceDetails() {

ResourceOwnerPasswordResourceDetails details = new ResourceOwnerPasswordResourceDetails();
details.setAccessTokenUri(tokenServiceUri);
details.setClientId(clientId);
details.setClientSecret(clientSecret);
details.setGrantType(grantType);
details.setUsername(username);
details.setPassword(password);

return details;
}


@Bean
public OAuth2RestTemplate cryptoKeycloakRestTemplate(OAuth2ClientContext clientContext) throws Exception {

// build template with custom SSL TrustStrategy

TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);

AuthorizationCodeAccessTokenProvider authCodeAccessTokenProvider = new AuthorizationCodeAccessTokenProvider();
authCodeAccessTokenProvider.setRequestFactory(requestFactory);

ImplicitAccessTokenProvider implicitAccessTokenProvider = new ImplicitAccessTokenProvider();
implicitAccessTokenProvider.setRequestFactory(requestFactory);

ResourceOwnerPasswordAccessTokenProvider resourceOwnerTokenProvider = new ResourceOwnerPasswordAccessTokenProvider();
resourceOwnerTokenProvider.setRequestFactory(requestFactory);

ClientCredentialsAccessTokenProvider clientCredentialsTokenProvider = new ClientCredentialsAccessTokenProvider();

AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(
Arrays.<AccessTokenProvider> asList(authCodeAccessTokenProvider, implicitAccessTokenProvider,
resourceOwnerTokenProvider, clientCredentialsTokenProvider));

AccessTokenRequest request = new DefaultAccessTokenRequest();
OAuth2RestTemplate template = new OAuth2RestTemplate(cryptoKeycloakResourceDetails(), new DefaultOAuth2ClientContext(request));
template.setAccessTokenProvider(accessTokenProvider);
template.setRequestFactory(requestFactory);
return template;
}
}



import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class KeycloakAdminQueryService {

@Autowired
private OAuth2RestOperations cryptoKeycloakRestTemplate;

@Value("${admin-query.admin-base-url}")
private String keycloakAdminQueryBaseUrl;

public KeycloakUserProfile getUserProfile(final String userId)
throws UserProfileNotFoundException {

Map<String,Object> uriVars = new HashMap<String,Object>();
uriVars.put("userId", userId);

try {
ResponseEntity<KeycloakUserProfile> response = cryptoKeycloakRestTemplate.getForEntity(
keycloakAdminQueryBaseUrl + "/users/{userId}", KeycloakUserProfile.class, uriVars);
return response.getBody();

} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
throw new UserProfileNotFoundException("Keycloak could not find user: " + userId, e);
} else {
throw e;
}
}
}
}



@Data
public class KeycloakUserProfile {

private String id;
private String createdTimestamp;
private String username;
private boolean enabled;
private boolean totp;
private boolean emailVerified;
private String firstName;
private String lastName;
private String email;
private List<String> disableableCredentialTypes;
private List<String> requiredActions;
private int notBefore;
private Access access;


@Data
public static class Access {
private boolean manageGroupMembership;
private boolean view;
private boolean mapRoles;
private boolean impersonate;
private boolean manage;
}

}

关于java - 使用 keycloak-admin-client 创建用户期间出现 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58818827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com