Keycloak实现手机验证码登录

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

背景说明

使用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统一的浏览器手机验证码登录

原理及实现

这种方式主要的工作原理是:

  1. 定制Keycloak登录主题,点击发送验证码有Keycloak服务进行验证码的发送,缓存和验证;

  2. 新增一个 keycloak-2fa-sms-authenticator 验证器,进行手机号和验证码的校验

具体实现代码可以参考:

在这里插入图片描述

对应的github地址

优缺点

优点是:

- 基于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

评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值