Keycloak访问冒充API

4
我们开始使用keycloak 3.4.3,并需要在我们的应用程序中引入一个模拟功能。我们发现keycloak有一个模拟api,不幸的是它不会为用户返回一个标记,而是返回一个重定向链接,用户可以在其中“选择”自己的客户端。
我们在这里找到了一种方法(用scala),可以检索一个新的令牌(仅适用于keycloak 3.4+): https://blog.softwaremill.com/who-am-i-keycloak-impersonation-api-bfe7acaf051a
    private def exchangeToken(token: String, userId: String): Future[TokenResponse] = {
  import io.circe.generic.auto._
  sttp
    .post(uri"${config.authServerUrl}/realms/${config.realm}/protocol/openid-connect/token")
    .body(
      "grant_type" -> "urn:ietf:params:oauth:grant-type:token-exchange",
      "client_id" -> config.clientId,
      "requested_subject" -> userId,
      "subject_token" -> token
    )
    .response(asJson[TokenResponse])
    .send()
    .flatMap {
      _.body match {
        case Left(error) => Future.failed(new RuntimeException(error))
        case Right(Left(circeError)) => Future.failed(circeError)
        case Right(Right(tokenResponse)) => Future.successful(tokenResponse)
      }
    }
}

我尝试基于它创建一个curl命令:

curl --verbose -X POST "http://<host>/auth/realms/master/protocol/openid-connect/token" \
 -H "Content-Type: application/x-www-form-urlencoded" \
 --data-urlencode "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
 -d 'client_id=admin_cli' \
 -d "requested_subject=${USER_ID}" \
 -d "subject_token=${TKN}" 

但是我收到了“invalid_client_credentials”错误。客户端“admin_cli”的访问类型为“public”。我尝试将授权令牌添加为承载者,但仍然收到相同的错误。
我是否忽略了某些配置?还是curl命令缺少某些参数?
感谢任何帮助。
2个回答

2

我希望现在回答不算太晚。我们可以使用模拟者(superadmin)的凭据来获取被模拟者(tony123)的访问令牌。以下是我遵循的步骤。

  1. 创建超级管理员用户。我给他分配了角色模拟,该角色可以在用户->超级管理员->角色映射->客户端角色->领域管理下找到。
  2. 使用以下方法获取超级管理员的访问令牌
curl --location --request POST 'http://localhost:8180/auth/realms/tenant/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'username=superadmin' \
--data-urlencode 'password=<superadmin-password>' \
--data-urlencode 'client_id=<source-client-id>' \
--data-urlencode 'client_secret=<source-client-secret>'

现在使用以下curl获取模拟用户的token。
curl --location --request POST 'http://localhost:8180/auth/realms/tenant/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=<source-client-id>' \
--data-urlencode 'client_secret=<source-client-secret>' \
--data-urlencode 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \
--data-urlencode 'subject_token=<access token got in step one>' \
--data-urlencode 'requested_token_type=urn:ietf:params:oauth:token-type:access_token' \
--data-urlencode 'requested_subject=<user id of tony123>'

1
我解决了这个问题,原来是curl命令中的一个简单的打字错误,admin_cli应该是admin-cli
谢谢。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接