Authenticator.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace fphammerle\yii2\auth\clientcert;
  3. class Authenticator extends \yii\base\Component
  4. {
  5. use \fphammerle\helpers\PropertyAccessTrait;
  6. public function init()
  7. {
  8. parent::init();
  9. $this->loginByClientCertficiate();
  10. }
  11. /**
  12. * @see \yii\web\User::switchIdentity
  13. * @return IdentityInterface|null
  14. */
  15. public function loginByDistinguishedName($dn, $duration = 0)
  16. {
  17. $subj = Subject::findByDistinguishedName($dn);
  18. if($subj) {
  19. \Yii::$app->user->switchIdentity($subj->identity, $duration);
  20. if(\Yii::$app->user->identity == $subj->identity) {
  21. return $subj->identity;
  22. } else {
  23. return null;
  24. }
  25. } else {
  26. return null;
  27. }
  28. }
  29. /**
  30. * @return bool
  31. */
  32. public function getClientCertVerified()
  33. {
  34. return isset($_SERVER['SSL_CLIENT_VERIFY'])
  35. && $_SERVER['SSL_CLIENT_VERIFY'] == 'SUCCESS';
  36. }
  37. /**
  38. * @return string|null
  39. */
  40. public function getClientCertSubjectDistinguishedName()
  41. {
  42. if(isset($_SERVER['SSL_CLIENT_S_DN'])) {
  43. return $_SERVER['SSL_CLIENT_S_DN'];
  44. } else {
  45. return null;
  46. }
  47. }
  48. /**
  49. * @return IdentityInterface|null
  50. */
  51. public function loginByClientCertficiate()
  52. {
  53. if($this->getClientCertVerified()) {
  54. // Subject DN in client certificate
  55. return $this->loginByDistinguishedName(
  56. $this->getClientCertSubjectDistinguishedName()
  57. );
  58. } else {
  59. return null;
  60. }
  61. }
  62. }