背景说明
使用Keycloak作为账号体系的项目中,经常会被问到Keycloak如何实现手机验证码登录,Keycloak有没有内置的基于短信的登录实现SMS-based two-/multi-factor-authentication (2FA/MFA) ;
Keycloak目前只内置一种基于 Google Authenticator 的 2FA 选项。
这篇主要讨论实现上述的需求的几种方案,以及相应的优缺点:
-
定制 Authentication SPI,实现Keycloak统一的浏览器手机验证码登录;
-
定制 Authentication SPI,实现基于 Resource Owner Password Credentials (Direct Access Grants)的手机验证码登录;
-
使用 token-exchange
-
使用 Identity Providers 实现手机验证码登录
定制 Authentication SPI,实现Keycloak统一的浏览器手机验证码登录
原理及实现
这种方式主要的工作原理是:
-
定制Keycloak登录主题,点击发送验证码有Keycloak服务进行验证码的发送,缓存和验证;
-
新增一个 keycloak-2fa-sms-authenticator 验证器,进行手机号和验证码的校验
具体实现代码可以参考:

优缺点
优点是:
- 基于Keycloak标准扩展实现,安全风险可控
- 基于浏览器登录,各业务统一的登录逻辑
缺点是:
- 浏览器登录在某些端,比如APP,并不适合
- 短信发送集成到Keycloak,各个业务无法再支持自定义模板及信息定义;
基于 Resource Owner Password Credentials (Direct Access Grants)的手机验证码登录
Direct Access Grants概念
Resource Owner Password Credentials Grant (Direct Access Grants)
This is referred to in the Admin Console as Direct Access Grants. This is used by REST clients that want to obtain a token on behalf of a user. It is one HTTP POST request that contains the credentials of the user as well as the id of the client and the client’s secret (if it is a confidential client). The user’s credentials are sent within form parameters. The HTTP response contains identity, access, and refresh tokens.
相关的 RESTApi请求
curl --location --request POST 'http://localhost:8080/auth/realms/austintest/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=server-admin' \
--data-urlencode 'client_secret=ee0c1f08-775d-4195-b5ca-19eb9b923822' \
--data-urlencode 'username=admin1' \
--data-urlencode 'password=123456' \
--data-urlencode 'grant_type=password'
在后台的 Keycloak

本文探讨了如何在Keycloak中实现手机验证码登录,包括自定义AuthenticationSPI、DirectAccessGrants、token-exchange和IdentityProviders的方法,及其优缺点,重点讲解了定制ValidateUserAttributeAuthenticator的详细步骤和应用场景.
最低0.47元/天 解锁文章
7901





