所以我有一个使用 api 的客户端。 API 由 keycloak 保护。
用户正常登录,但我希望允许用户登录用户,而无需使用他们的社交媒体帐户(如 facebook 或 google)访问 keycloak 的登录页面。
我需要一个包含如何获取生成 url 的实现的 rest API,以便当用户在按钮中单击此 url 时,它将把用户带到相应的社交登录页面进行登录,而 keycloak 仍然充当代理。
下面是我的实现,它生成了一个 url,但不会将用户带到 google 页面登录
这是一个休息 Controller
@Secured("permitAll")
@GetMapping(path = "/generator")
public String brokerGenerator(HttpServletRequest httpServletRequest) throws ServletException {
String provider = "google";
String authServerRootUrl = "http://localhost:8080/";
String realm = "realmName";
String clientId = "clientName";
String nonce = UUID.randomUUID().toString();
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
String input = nonce + clientId + provider;
byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
String hash = Base64Url.encode(check);
httpServletRequest.getSession().setAttribute("hash", hash);
String redirectUri = "http://localhost:4200/dashboard";
return KeycloakUriBuilder.fromUri(authServerRootUrl)
.path("auth/realms/realmName/google/link")
.queryParam("nonce", nonce)
.queryParam("hash", hash)
.queryParam("client_id", clientId)
.queryParam("redirect_uri", redirectUri).build(realm, provider).toString();
}
最佳答案
Keycloak 支持开箱即用。见 https://www.keycloak.org/docs/6.0/server_admin/#_client_suggested_idp
OIDC applications can bypass the Keycloak login page by specifying a hint on which identity provider they want to use.
This is done by setting the kc_idp_hint query parameter in the Authorization Code Flow authorization endpoint.
更新
在您的情况下,您应该使用普通的 Keycloak Auth Code Flow 端点,并且除了基本查询参数之外还提供
kc_idp_hint
参数。这样,用户首先被重定向到 Keycloak 登录页面,然后 Keycloak 将他重定向到所选的身份提供者登录页面(在您的情况下为 google)。这是一个示例重定向 URL:
https://keycloak-domain/realms/REALM_NAME/protocol/openid-connect/auth?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&state=STATE&response_type=code&scope=openid&nonce=NONCE&kc_idp_hint=google
根据此示例编辑您的代码:return KeycloakUriBuilder.fromUri(authServerRootUrl)
.path("realms/realmName/protocol/openid-connect/auth") // Url changed
.queryParam("response_type", "code") // Autherization Code Flow
.queryParam("scope", "openid") // Add additional scopes if needed
.queryParam("kc_idp_hint", "google") // This should match IDP name registered in Keycloak
.queryParam("nonce", nonce)
.queryParam("hash", hash)
.queryParam("client_id", clientId)
.queryParam("redirect_uri", redirectUri).build(realm, provider).toString();
您可以手动启动 Keycloak 重定向进行测试。启动正常的登录流程,当您重定向到 Keycloak 登录页面时,不要输入凭据,而是添加 kc_idp_hint=google
到 URL 并按 ENTER。然后您将被直接重定向到 Google 登录页面。
关于java - Keycloak 身份代理 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56776381/