Keycloak一次性使用令牌

时间:2019-11-19 16:00:25

标签: keycloak

我们需要生成一次使用令牌,并将其用于密码重置电子邮件中。 Keycloak是否提供任何标准API来生成和验证一次性令牌?。

我们正在使用OIDC Rsource所有者密码凭据授予(用于身份验证的直接访问授予。

2 个答案:

答案 0 :(得分:0)

您可以实现自定义的操作令牌SPI和必需的操作SPI。它将生成所需的令牌,然后向用户挑战。

https://www.keycloak.org/docs/7.0/server_development/index.html#_action_token_spi

答案 1 :(得分:0)

Anatomy of Action Token

nonce-如果操作只能执行一次(可选),则随机使用nonce以保证使用的唯一性。这是您的应用程序必须生成的随机字符串。

下面是一个Java Servlet代码示例,该示例生成用于建立帐户链接的URL。

​KeycloakSecurityContext session = (KeycloakSecurityContext) httpServletRequest.getAttribute(KeycloakSecurityContext.class.getName());
​AccessToken token = session.getToken();
​String clientId = token.getIssuedFor();
​String nonce = UUID.randomUUID().toString();
​MessageDigest md = null;
​try {
   ​md = MessageDigest.getInstance("SHA-256");
​} catch (NoSuchAlgorithmException e) {
   ​throw new RuntimeException(e);
​}
​String input = nonce + token.getSessionState() + clientId + provider;
​byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
​String hash = Base64Url.encode(check);
​request.getSession().setAttribute("hash", hash);
​String redirectUri = ...;
​String accountLinkUrl = KeycloakUriBuilder.fromUri(authServerRootUrl)
                 ​.path("/auth/realms/{realm}/broker/{provider}/link")
                 ​.queryParam("nonce", nonce)
                 ​.queryParam("hash", hash)
                 ​.queryParam("client_id", clientId)
                 ​.queryParam("redirect_uri", redirectUri).build(realm, provider).toString();