Keycloak不刷新令牌

时间:2020-10-07 10:40:42

标签: authentication oauth-2.0 jwt keycloak

我正在尝试刷新令牌,但Keycloak返回400 Bad Request错误并显示以下消息:

{
    "error": "invalid_grant",
    "error_description": "Invalid refresh token"
}

我在这样的请求中成功获取了刷新令牌:

curl --location --request POST 'http://localhost:8080/auth/realms/my_realm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'username=my_user' \
--data-urlencode 'password=my_password' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'client_id=my_client_id' \
--data-urlencode 'client_secret=my_client_secret'

所以我得到一个带有访问令牌和刷新令牌的JWT响应。当我将它们加载到jwt.io中时,它们似乎都有效。

但是当我尝试使用刷新令牌时,出现了先前的错误。该请求是这样的:

curl --location --request POST 'http://localhost:8080/auth/realms/my_realm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=my_client_id' \
--data-urlencode 'grant_type=refresh_token' \
--data-urlencode 'refresh_token=my_refresh_token' \
--data-urlencode 'client_secret=my_client_secret'

在Keycloak的日志中,没有任何问题的线索。

这可能是原因吗?或者至少,有一种方法可以从Keycloak的响应或日志中获取有关错误原因的更多信息?

编辑:

我已经实现了一个用户存储提供者SPI,因此它可以对外部数据库进行身份验证,但不能将用户管理到Keycloak中。是否需要令牌所有者用户存在于Keycloak中才能刷新令牌?

谢谢。

1 个答案:

答案 0 :(得分:0)

最后,这是我的用户存储提供者SPI中的一个问题。由于Keycloak从刷新令牌中获取用户ID并通过该ID查找用户,因此必须实现以下方法:

public UserModel getUserById(String id, RealmModel realm) {
    StorageId storageId = new StorageId(id);
    String username = storageId.getExternalId();
    return getUserByUsername(username, realm);
}