Authenticator.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 IdentityInterface|null
  39. */
  40. public function loginByClientCertficiate()
  41. {
  42. if($this->getClientCertVerified()) {
  43. // Subject DN in client certificate
  44. return $this->loginByDistinguishedName($_SERVER["SSL_CLIENT_S_DN"]);
  45. } else {
  46. return null;
  47. }
  48. }
  49. }