且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过API集成Keycloak短信身份验证?

更新时间:2023-12-01 08:12:34

我找到了解决方案. 要在不知道他人密码的情况下登录,请执行以下操作:

I found a solution. To login without knowing someone's password:

  1. 发送短信;
  2. 通过代码确认电话号码;
  3. 获取目标用户的密钥库ID;
  4. 以有权假冒;
  5. 与目标用户交换令牌.
  1. Send SMS;
  2. Confirm phone number by a code;
  3. Get the keycloak ID of a target user;
  4. Log in as a user having the right to impersonate;
  5. Exchange tokens with a target user.

TOKEN_EXCHANGE密钥斗篷功能.

我使用Laravel实现了步骤1-3,使用Keycloak API实现了步骤4-5:

Steps 1-3 I implemented with Laravel, steps 4-5 with Keycloak APIs:

public function loginByUserId(string $userId): SsoTokens
    {
        try {
            $impersonatorData = $this->realmEndpoint->makeRequest(
                HttpClientProvider::METHOD_POST,
                self::KEYCLOAK_AUTH_URL,
                [
                    'client_id' => config('services.keycloak.realm_client'),
                    'client_secret' => config('services.keycloak.realm_secret'),
                    'grant_type' => 'password',
                    'username' => config('services.keycloak.admin_username'),
                    'password' => config('services.keycloak.admin_password'),
                    'scope' => 'openid',
                ]
            );

            $data = $this->realmEndpoint->makeRequest(
                HttpClientProvider::METHOD_POST,
                self::KEYCLOAK_AUTH_URL,
                [
                    'client_id' => config('services.keycloak.realm_client'),
                    'client_secret' => config('services.keycloak.realm_secret'),
                    'grant_type' => 'urn:ietf:params:oauth:grant-type:token-exchange',
                    'requested_subject' => $userId,
                    'subject_token' => $impersonatorData['access_token'],
                    'scope' => 'openid',
                ]
            );
        } catch (TransportUnauthorizedException $e) {
            throw new UnauthorizedException($e);
        } catch (HttpClientException $e) {
            throw new TransportException($e);
        }

        return $this->extractTokens($data);
    }