所以我有一个使用 api 的客户端。API 由 keycloak 保护。用户正常登录,但我希望允许用户登录用户,而不必使用他们的社交媒体帐户(如 facebook 或 google)访问 keycloak 的登录页面。我需要一个 rest API,其中包含如何生成 url 的实现,因此当用户在按钮中单击此 url 时,它将把用户带到相应的社交登录页面进行登录,而 keycloak 仍然充当代理。下面是我的实现,它可以生成一个 url,但不会将用户带到 google 页面进行登录这是一个休息控制器 @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(); }
1 回答

泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
Keycloak 开箱即用地支持这一点。请参阅https://www.keycloak.org/docs/latest/server_admin/index.html#_client_suggested_idp
OIDC 应用程序可以通过指定他们想要使用哪个身份提供者的提示来绕过 Keycloak 登录页面。
这是通过在授权代码流授权端点中设置 kc_idp_hint 查询参数来完成的。
更新
在您的情况下,您应该使用普通的 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 登录页面。
添加回答
举报
0/150
提交
取消