Authenticator.php 1.6 KB

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