Example #1
0
 /**
  * Construct an authnresponse and send it.
  * Also test setting a relaystate and destination for the response.
  */
 public function testSendAuthnResponse()
 {
     $response = new Response();
     $response->setIssuer('testIssuer');
     $response->setRelayState('http://example.org');
     $response->setDestination('http://example.org/login?success=yes');
     $response->setSignatureKey(CertificatesMock::getPrivateKey());
     $hr = new HTTPPost();
     $hr->send($response);
 }
 public static function handleLoginRequest(IPerson $Person)
 {
     try {
         $binding = Binding::getCurrentBinding();
     } catch (Exception $e) {
         return static::throwUnauthorizedError('Cannot obtain SAML2 binding');
     }
     $request = $binding->receive();
     // build response
     $response = new Response();
     $response->setInResponseTo($request->getId());
     $response->setRelayState($request->getRelayState());
     $response->setDestination($request->getAssertionConsumerServiceURL());
     // build assertion
     $assertion = new Assertion();
     $assertion->setIssuer(static::$issuer);
     $assertion->setSessionIndex(ContainerSingleton::getInstance()->generateId());
     $assertion->setNotBefore(time() - 30);
     $assertion->setNotOnOrAfter(time() + 300);
     $assertion->setAuthnContext(SAML2_Constants::AC_PASSWORD);
     // build subject confirmation
     $sc = new SubjectConfirmation();
     $sc->Method = SAML2_Constants::CM_BEARER;
     $sc->SubjectConfirmationData = new SubjectConfirmationData();
     $sc->SubjectConfirmationData->NotOnOrAfter = $assertion->getNotOnOrAfter();
     $sc->SubjectConfirmationData->Recipient = $request->getAssertionConsumerServiceURL();
     $sc->SubjectConfirmationData->InResponseTo = $request->getId();
     $assertion->setSubjectConfirmation([$sc]);
     // set NameID
     $assertion->setNameId(['Format' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress', 'Value' => $Person->Username . '@' . static::$issuer]);
     // set additional attributes
     $assertion->setAttributes(['User.Email' => [$Person->Email], 'User.Username' => [$Person->Username]]);
     // attach assertion to response
     $response->setAssertions([$assertion]);
     // create signature
     $privateKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, ['type' => 'private']);
     $privateKey->loadKey(static::$privateKey);
     $response->setSignatureKey($privateKey);
     $response->setCertificates([static::$certificate]);
     // prepare response
     $responseXML = $response->toSignedXML();
     $responseString = $responseXML->ownerDocument->saveXML($responseXML);
     // dump response and quit
     #        header('Content-Type: text/xml');
     #        die($responseString);
     // send response
     $responseBinding = new HTTPPost();
     $responseBinding->send($response);
 }
 /**
  * @param string $returnTo Where to have IdP send user after login
  * @param \yii\web\Request|null $request
  * @return \Sil\IdpPw\Common\Auth\User
  * @throws \Sil\IdpPw\Common\Auth\InvalidLoginException
  * @throws RedirectException
  */
 public function login($returnTo, Request $request = null)
 {
     $container = new SamlContainer();
     ContainerSingleton::setContainer($container);
     $request = new AuthnRequest();
     $request->setId($container->generateId());
     $request->setIssuer($this->entityId);
     $request->setDestination($this->ssoUrl);
     $request->setRelayState($returnTo);
     /*
      * Sign request if spCertificate and spPrivateKey are provided
      */
     if ($this->signRequest) {
         $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, ['type' => 'private']);
         $key->loadKey($this->spPrivateKey, false);
         $request->setSignatureKey($key);
     }
     try {
         /*
          * Check for SAMLRequest or SAMLResponse to see if user is returning after login
          */
         $binding = new HTTPPost();
         /** @var \SAML2\Response $response */
         $response = $binding->receive();
     } catch (\Exception $e) {
         /*
          * User was not logged in, so redirect to IdP for login
          */
         $binding = new HTTPRedirect();
         $url = $binding->getRedirectURL($request);
         throw new RedirectException($url);
     }
     try {
         /*
          * If needed, check if response is signed
          */
         if ($this->checkResponseSigning) {
             $idpKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, ['type' => 'public']);
             $idpKey->loadKey($this->idpCertificate, false, true);
             if (!$response->validate($idpKey)) {
                 throw new \Exception('SAML response was not signed properly', 1459884735);
             }
         }
         /** @var \SAML2\Assertion[]|\SAML2\EncryptedAssertion[] $assertions */
         $assertions = $response->getAssertions();
         /*
          * If requiring encrypted assertion, use key to decrypt it
          */
         if ($this->requireEncryptedAssertion) {
             $decryptKey = new XMLSecurityKey(XMLSecurityKey::RSA_OAEP_MGF1P, ['type' => 'private']);
             $decryptKey->loadKey($this->spPrivateKey, false, false);
             if (!$assertions[0] instanceof EncryptedAssertion) {
                 throw new \Exception('Response assertion is required to be encrypted but was not', 1459884392);
             }
             $assertion = $assertions[0]->getAssertion($decryptKey);
         } else {
             $assertion = $assertions[0];
         }
         /*
          * Get attributes using mapping config, make sure expected fields
          * are present, and return as new User
          */
         /** @var \SAML2\Assertion $assertion */
         $samlAttrs = $assertion->getAttributes();
         $normalizedAttrs = $this->extractSamlAttributes($samlAttrs, $this->attributeMap);
         $this->assertHasRequiredSamlAttributes($normalizedAttrs, $this->attributeMap);
         $authUser = new AuthUser();
         $authUser->firstName = $normalizedAttrs['first_name'];
         $authUser->lastName = $normalizedAttrs['last_name'];
         $authUser->email = $normalizedAttrs['email'];
         $authUser->employeeId = $normalizedAttrs['employee_id'];
         $authUser->idpUsername = $normalizedAttrs['idp_username'];
         return $authUser;
     } catch (\Exception $e) {
         /*
          * An error occurred processing SAML data
          */
         throw new InvalidLoginException($e->getMessage(), 1459803743);
     }
 }