我一直在查看 Keycloak 文档,但看不到如何执行此操作。使用 Java,我想获取一个有效的用户 ID 和密码,然后生成一个令牌。我怎样才能做到这一点?
元芳怎么了
浏览 455回答 1
1回答
拉丁的传说
您可以使用授权客户端 Java API。创建 AuthzClient 对象后,您可以将用户名和密码传递给AuthzClient#authorization(username, password)或AuthzClient#obtainAccessToken(username, password)方法以对用户进行身份验证并获取访问令牌(和/或 ID 令牌)在第一种情况下):// create a new instance based on the configuration defined in keycloak-authz.jsonAuthzClient authzClient = AuthzClient.create();// send the authorization request to the server in order to// obtain an access token granted to the userAccessTokenResponse response = authzClient.obtainAccessToken("alice", "alice");附带说明一下,如果可能,您宁愿重用Keycloak Java 适配器之一来涵盖更多功能,例如其他身份验证方法(用户通常被重定向到 Keycloack WUI,您可以在其中执行非常灵活的身份验证和授权策略)。