告别身份验证难题:如何使用Smart-IDPHPClient实现安全便捷的身份验证

发布时间 - 2025-09-01 00:00:00    点击率:

在构建需要安全身份验证的 Web 应用程序时,我遇到了一个常见的问题:如何集成一个既安全又用户友好的身份验证解决方案。传统的用户名/密码方式已经无法满足日益增长的安全需求,而复杂的双因素认证方案又可能降低用户体验。

这时,我发现了 smart-id,一种基于移动设备的数字身份验证解决方案。smart-id 允许用户使用他们的移动设备进行身份验证,无需记住复杂的密码或携带额外的硬件设备。然而,如何将 smart-id 集成到我的 php 应用程序中,成为了一个新的挑战。

经过一番研究,我找到了

sk-id-solutions/smart-id-php-client
这个 Composer 包,它提供了一个简洁的 PHP 接口,可以轻松地与 Smart-ID 服务进行交互。

安装

首先,你需要使用 Composer 安装该库:

composer require sk-id-solutions/smart-id-php-client "2.3.2"

配置客户端

安装完成后,你需要配置客户端的详细信息,包括 Relying Party UUID、Relying Party Name 和 Smart-ID 服务的 URL。更重要的是,为了防止中间人攻击,你需要设置 HTTPS pinning,通过指定信任的 SSL 证书的公钥哈希来确保与 Smart-ID 服务的安全连接。

use SK\SmartId\Client\Client;

$this->client = new Client();
$this->client
    ->setRelyingPartyUUID( '00000000-0000-0000-0000-000000000000' ) // In production replace with your UUID
    ->setRelyingPartyName( 'DEMO' ) // In production replace with your name
    ->setHostUrl( 'https://sid.demo.sk.ee/smart-id-rp/v2/' ) // In production replace with production service URL
        // in production replace with correct server SSL key
    ->setPublicSslKeys("sha256//Ps1Im3KeB0Q4AlR+/J9KFd/MOznaARdwo4gURPCLaVA=");

使用语义标识符进行身份验证

接下来,你可以使用语义标识符(例如个人身份号码)来启动身份验证流程。这个过程包括生成一个随机的身份验证哈希,并将其呈现给用户,以便他们在 Smart-ID 应用程序中进行验证。

use SK\SmartId\Client\Api\Authentication\AuthenticationRequestBuilder;
use SK\SmartId\Client\Api\Authentication\AuthenticationResponseValidator;
use SK\SmartId\Client\Api\Authentication\NationalIdentity;
use SK\SmartId\Client\Api\Authentication\SemanticsIdentifier;
use SK\SmartId\Client\Api\SessionStatus\SessionStatusResponse;
use SK\SmartId\Client\Exception\UserRefusedException;
use SK\SmartId\Client\Exception\UserSelectedWrongVerificationCodeException;
use SK\SmartId\Client\Exception\SessionTimeoutException;
use SK\SmartId\Client\Exception\UserAccountNotFoundException;
use SK\SmartId\Client\Exception\UserAccountException;
use SK\SmartId\Client\Exception\EnduringSmartIdException;
use SK\SmartId\Client\Exception\SmartIdException;
use SK\SmartId\Client\Util\AuthenticationHash;
use SK\SmartId\Client\Api\Authentication\CertificateLevelCode;
use SK\SmartId\Client\Api\Authentication\Interaction;

$semanticsIdentifier = SemanticsIdentifier::builder()
    ->withSemanticsIdentifierType('PNO')
    ->withCountryCode('LT')
    ->withIdentifier('30303039914')
    ->build();

// For security reasons a new hash value must be created for each new authentication request
$authenticationHash = AuthenticationHash::generate();

$verificationCode = $authenticationHash->calculateVerificationCode();

// display verification code to the user
echo "Verification code: " . $verificationCode . "\n";

$authenticationResponse = null;
try
{
  $authenticationResponse = $this->client->authentication()
      ->createAuthentication()
      ->withSemanticsIdentifier( $semanticsIdentifier )
      ->withAuthenticationHash( $authenticationHash )
      ->withCertificateLevel( CertificateLevelCode::QUALIFIED ) // Certificate level can either be "QUALIFIED" or "ADVANCED"
      ->withAllowedInteractionsOrder((array(
          Interaction::ofTypeVerificationCodeChoice("Enter awesome portal?"),
          Interaction::ofTypeDisplayTextAndPIN("Enter awesome portal?"))))
      ->authenticate(); // this blocks until user has responded
}
catch (UserRefusedException $e) {
  throw new RuntimeException("You pressed cancel in Smart-ID app.");
}
catch (UserSelectedWrongVerificationCodeException $e) {
  throw new RuntimeException("You selected wrong verification code in Smart-ID app. Please try again. ");
}
catch (SessionTimeoutException $e) {
  throw new RuntimeException("Session timed out (you didn't enter PIN1 in Smart-ID app).");
}
catch (UserAccountNotFoundException $e) {
  throw new RuntimeException("User does not have a Smart-ID account");
}
catch (UserAccountException $e) {
  throw new RuntimeException("Unable to authenticate due to a problem with your Smart-ID account.");
}
catch (EnduringSmartIdException $e) {
  throw new RuntimeException("Problem with connecting to Smart-ID service. Please try again later.");
}
catch (SmartIdException $e) {
  throw new RuntimeException("Smart-ID authentication process failed for uncertain reason: ". $e);
}

// create a folder with name "trusted_certificates" and set path to that folder here:
$pathToFolderWithTrustedCertificates = __DIR__ . '/../../../resources';

$authenticationResponseValidator = new AuthenticationResponseValidator($pathToFolderWithTrustedCertificates);
$authenticationResult = $authenticationResponseValidator->validate( $authenticationResponse );


if ($authenticationResult->isValid()) {
  echo "Hooray! Authentication result is valid";
}
else {
   throw new RuntimeException("Error! Response is not valid! Error(s): ". implode(",", $authenticationResult->getErrors()));
}



$authenticationIdentity = $authenticationResult->getAuthenticationIdentity();

echo "hello name: " . $authenticationIdentity->getGivenName() . ' ' . $authenticationIdentity->getSurName() . "\n";
echo "from " . $authenticationIdentity->getCountry() . "\n";
echo "born " . $authenticationIdentity->getDateOfBirth()->format("D d F o") . "\n";

// you might need this if you want to start authentication with document number
echo "Authenticated user documentNumber is: ".$authenticationResponse->getDocumentNumber(). "\n";

处理异常

在身份验证过程中,可能会出现各种异常情况,例如用户取消操作、选择错误的验证码、会话超时等等。该库提供了专门的异常类来处理这些情况,你可以使用 try-catch 块来捕获这些异常并采取适当的措施。

验证身份验证结果

为了确保身份验证结果的真实性,你需要验证 Smart-ID 服务的签名。这需要你配置一个包含受信任证书的目录,并使用

AuthenticationResponseValidator
类来验证签名。

通过使用

sk-id-solutions/smart-id-php-client
库,我能够轻松地将 Smart-ID 集成到我的 PHP 应用程序中,并提供了一个安全、便捷的身份验证体验。该库的优点包括:

  • 简单易用: 提供了简洁的 API,可以轻松地与 Smart-ID 服务进行交互。
  • 安全性高: 支持 HTTPS pinning,可以防止中间人攻击。
  • 异常处理: 提供了专门的异常类来处理各种身份验证错误。
  • 结果验证: 提供了验证身份验证结果真实性的机制。

sk-id-solutions/smart-id-php-client
库极大地简化了 Smart-ID 集成过程,使我能够专注于构建应用程序的核心功能,而无需担心复杂的身份验证细节。如果你正在寻找一种安全、便捷的身份验证解决方案,那么 Smart-ID 和
sk-id-solutions/smart-id-php-client
库绝对值得考虑。

Composer在线学习地址:学习地址


# composer  # css  # php  # ai  # try  # catch  # 标识符  # 接口  # https  # ssl  # 身份验证  # 应用程序  # 你可以  # 的是  # 客户端  # 他们的  # 如果你  # 更重要  # 使我  # 我找 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 香港代理服务器配置指南:高匿IP选择、跨境加速与SEO优化技巧  浏览器如何快速切换搜索引擎_在地址栏使用不同搜索引擎【搜索】  linux写shell需要注意的问题(必看)  为什么php本地部署后css不生效_静态资源加载失败修复技巧【技巧】  Laravel如何处理文件上传_Laravel Storage门面实现文件存储与管理  如何快速配置高效服务器建站软件?  php结合redis实现高并发下的抢购、秒杀功能的实例  制作公司内部网站有哪些,内网如何建网站?  微信小程序 wx.uploadFile无法上传解决办法  JS实现鼠标移上去显示图片或微信二维码  JS中使用new Date(str)创建时间对象不兼容firefox和ie的解决方法(两种)  开心动漫网站制作软件下载,十分开心动画为何停播?  怎么制作一个起泡网,水泡粪全漏粪育肥舍冬季氨气超过25ppm,可以有哪些措施降低舍内氨气水平?  如何快速生成橙子建站落地页链接?  网站广告牌制作方法,街上的广告牌,横幅,用PS还是其他软件做的?  如何破解联通资金短缺导致的基站建设难题?  Laravel Vite是做什么的_Laravel前端资源打包工具Vite配置与使用  Win11怎么开启自动HDR画质_Windows11显示设置HDR选项  如何用已有域名快速搭建网站?  高防服务器租用首荐平台,企业级优惠套餐快速部署  利用JavaScript实现拖拽改变元素大小  Laravel如何使用Seeder填充数据_Laravel模型工厂Factory批量生成测试数据【方法】  EditPlus中的正则表达式 实战(1)  网站建设保证美观性,需要考虑的几点问题!  Laravel怎么实现观察者模式Observer_Laravel模型事件监听与解耦开发【指南】  详解jQuery停止动画——stop()方法的使用  Laravel如何实现邮箱地址验证功能_Laravel邮件验证流程与配置  Laravel如何处理和验证JSON类型的数据库字段  bootstrap日历插件datetimepicker使用方法  高端云建站费用究竟需要多少预算?  Zeus浏览器网页版官网入口 宙斯浏览器官网在线通道  JS中对数组元素进行增删改移的方法总结  家族网站制作贴纸教程视频,用豆子做粘帖画怎么制作?  Laravel如何实现密码重置功能_Laravel密码找回与重置流程  网站制作免费,什么网站能看正片电影?  Python自动化办公教程_ExcelWordPDF批量处理案例  香港服务器部署网站为何提示未备案?  标题:Vue + Vuex 项目中正确使用 JWT 进行身份认证的实践指南  jQuery中的100个技巧汇总  Edge浏览器如何截图和滚动截图_微软Edge网页捕获功能使用教程【技巧】  公司网站制作需要多少钱,找人做公司网站需要多少钱?  微信小程序 配置文件详细介绍  如何生成腾讯云建站专用兑换码?  JavaScript如何实现音频处理_Web Audio API如何工作?  Win10如何卸载预装Edge扩展_Win10卸载Edge扩展教程【方法】  如何在云主机上快速搭建网站?  Laravel如何集成Inertia.js与Vue/React?(安装配置)  javascript中的数组方法有哪些_如何利用数组方法简化数据处理  如何快速搭建FTP站点实现文件共享?  Python自然语言搜索引擎项目教程_倒排索引查询优化案例