Create a new SAML1 response object.

@param authnStatement the authn statement
@param issuer         the issuer
@param issuedAt       the issued at
@param id             the id
@return the assertion
506042
public Assertion newAssertion(final List<Statement> authnStatement, final String issuer,
                                  final ZonedDateTime issuedAt, final String id) {
        val assertion = newSamlObject(Assertion.class);
        assertion.setID(id);
        assertion.setIssueInstant(DateTimeUtils.dateTimeOf(issuedAt));
        assertion.setIssuer(newIssuer(issuer));
        assertion.getStatements().addAll(authnStatement);
        return assertion;
    }
492093
def _make_authorization_grant_assertion(self):
        
        now = _helpers.utcnow()
        lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
        expiry = now + lifetime

        payload = {
            'iat': _helpers.datetime_to_secs(now),
            'exp': _helpers.datetime_to_secs(expiry),
            # The issuer must be the service account email.
            'iss': self.service_account_email,
            # The audience must be the auth token endpoint's URI
            'aud': self._token_uri,
            # The target audience specifies which service the ID token is
            # intended for.
            'target_audience': self._target_audience
        }

        payload.update(self._additional_claims)

        token = jwt.encode(self._signer, payload)

        return token
573409
@Transactional
    @Override
    public OAuthAuthorizationCode create(OAuthAuthorizationCode authCodeEntity) {
        requireNotDisposed();
        requireArgument(StringUtils.isNotBlank(authCodeEntity.getAuthorizationCode()), "authorization_code cannot be null or empty");
        requireArgument(StringUtils.isNotBlank(authCodeEntity.getState()), "state cannot be null or empty");
        requireArgument(StringUtils.isNotBlank(authCodeEntity.getRedirectUri()), "Redirect URI cannot be null or empty");
        requireArgument(authCodeEntity != null, "Cannot update a null authorization code entity");
        EntityManager em = emf.get();
        OAuthAuthorizationCode result = em.merge(authCodeEntity);
        em.flush();
        _logger.debug("Created OAuthAuthorizationCode to : {}", result);
        return result;
    }
101989
public Response newResponse(final String id, final ZonedDateTime issueInstant,
                                final String recipient, final WebApplicationService service) {

        val samlResponse = newSamlObject(Response.class);
        samlResponse.setID(id);
        samlResponse.setIssueInstant(DateTimeUtils.dateTimeOf(issueInstant));
        samlResponse.setVersion(SAMLVersion.VERSION_20);
        if (StringUtils.isNotBlank(recipient)) {
            LOGGER.debug("Setting provided RequestId [{}] as InResponseTo", recipient);
            samlResponse.setInResponseTo(recipient);
        } else {
            LOGGER.debug("No recipient is provided. Skipping InResponseTo");
        }
        return samlResponse;
    }
932338
def _issuer(self, entityid=None):
        
        if entityid:
            if isinstance(entityid, Issuer):
                return entityid
            else:
                return Issuer(text=entityid, format=NAMEID_FORMAT_ENTITY)
        else:
            return Issuer(text=self.config.entityid,
                          format=NAMEID_FORMAT_ENTITY)
344528
private void setIssuer(Object val) throws CertificateException {
        if (!(val instanceof X500Name)) {
            throw new CertificateException(
                             "Issuer class type invalid.");
        }
        issuer = (X500Name)val;
    }
160324
public static String signSamlResponse(final String samlResponse, final PrivateKey privateKey, final PublicKey publicKey) {
        val doc = constructDocumentFromXml(samlResponse);

        if (doc != null) {
            val signedElement = signSamlElement(doc.getRootElement(),
                privateKey, publicKey);
            doc.setRootElement((org.jdom.Element) signedElement.detach());
            return new XMLOutputter().outputString(doc);
        }
        throw new IllegalArgumentException("Error signing SAML Response: Null document");
    }
1310018
public static String createAuthenticateHeader(final String realm, final String authMethod, final String nonce) {
        val stringBuilder = new StringBuilder("Digest realm=\"")
            .append(realm).append("\",");
        if (StringUtils.isNotBlank(authMethod)) {
            stringBuilder.append("qop=").append(authMethod).append(',');
        }
        return stringBuilder.append("nonce=\"").append(nonce)
            .append("\",opaque=\"").append(createOpaque(realm, nonce))
            .append('"')
            .toString();
    }
1155705
public Element requestSecurityTokenResponse(final String appliesTo, final String action,
                                                final String requestType, final SecurityToken target) throws Exception {
        val response = issue(appliesTo, null, "/Issue", null);
        return getDocumentElement(response.getResponse());
    }
75978
protected void initiateAuthenticationRequest(final Pair<? extends SignableSAMLObject, MessageContext> pair,
                                                 final HttpServletResponse response,
                                                 final HttpServletRequest request) throws Exception {

        verifySamlAuthenticationRequest(pair, request);
        issueAuthenticationRequestRedirect(pair, request, response);
    }
1330768
private void sendAsyncAuthenticationRequest(final int appId, final String bridgeId,
      final CallStatsHttp2Client httpClient) {
    synchronized (isAuthenticationInProgress) {
      if (isAuthenticationInProgress)
        return;
      isAuthenticationInProgress = true;

    }
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("client_id", bridgeId + "@" + appId));
    params.add(new NameValuePair("code", tokenGenerator.generateToken(forcenewtoken)));
    params.add(new NameValuePair("grant_type", "authorization_code"));

    httpClient.sendAuthRequest(authenticateUrl, params, new CallStatsHttp2ResponseListener() {
      public void onResponse(Response response) {
        isAuthenticationInProgress = false;
        int responseStatus = response.code();
        if (responseStatus == CallStatsResponseStatus.RESPONSE_STATUS_SUCCESS) {
          AuthenticateResponse authResponseMessage;
          String responseString;
          try {
            responseString = response.body().string();
            authResponseMessage = gson.fromJson(responseString, AuthenticateResponse.class);
          } catch (Exception e) {
            e.printStackTrace();
            listener.onError(CallStatsErrors.HTTP_ERROR, e.getMessage());
            scheduleAuthentication(appId, bridgeId, httpClient);
            return;
          }
          logger.info(
              "Authentication response " + responseStatus + " " + authResponseMessage.getToken());
          // expires = authResponseMessage.getAuthenticateBody().getExpires();
          token = authResponseMessage.getToken();
          CallStatsConfigProvider.setURLs(authResponseMessage.getMetadata().getEventsUrl(),
              authResponseMessage.getMetadata().getStatsUrl());
          listener.onInitialized(authSuccessString);
        } else if (responseStatus == CallStatsResponseStatus.INVALID_REQUEST) {
          AuthenticateResponseError authResponseMessageError;
          String responseString;
          try {
            responseString = response.body().string();
            authResponseMessageError =
                gson.fromJson(responseString, AuthenticateResponseError.class);
          } catch (Exception e) {
            e.printStackTrace();
            listener.onError(CallStatsErrors.HTTP_ERROR, e.getMessage());
            scheduleAuthentication(appId, bridgeId, httpClient);
            return;
          }
          for (AuthenticateErrorAction action : authResponseMessageError.getErrorActions()) {
            if (action.getAction() == AuthenticateErrorActionType.GET_NEW_TOKEN) {
              forcenewtoken = true;
            } else if (action.getAction() == AuthenticateErrorActionType.RETRY) {
              authenticationRetryTimeout =
                  ((AuthenticateRetryActionParams) action.getParams()).getTimeout();
              scheduleAuthentication(appId, bridgeId, httpClient);
            }
          }
          listener.onError(CallStatsErrors.AUTH_ERROR, authErrString);
        } else if (responseStatus == CallStatsResponseStatus.GATEWAY_ERROR) {
          scheduleAuthentication(appId, bridgeId, httpClient);
          listener.onError(CallStatsErrors.APP_CONNECTIVITY_ERROR, authErrString);
        } else {
          scheduleAuthentication(appId, bridgeId, httpClient);
          listener.onError(CallStatsErrors.HTTP_ERROR, authErrString);
        }

      }


      public void onFailure(Exception e) {
        isAuthenticationInProgress = false;
        listener.onError(CallStatsErrors.HTTP_ERROR, e.getMessage());
      }

    });
  }
623426
protected Authentication authenticateEcpRequest(final Credential credential,
                                                    final Pair<AuthnRequest, MessageContext> authnRequest) {
        val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest.getKey());
        LOGGER.debug("Located issuer [{}] from request prior to authenticating [{}]", issuer, credential.getId());

        val service = getSamlProfileHandlerConfigurationContext().getWebApplicationServiceFactory().createService(issuer);
        LOGGER.debug("Executing authentication request for service [{}] on behalf of credential id [{}]", service, credential.getId());
        val authenticationResult = getSamlProfileHandlerConfigurationContext()
            .getAuthenticationSystemSupport().handleAndFinalizeSingleAuthenticationTransaction(service, credential);
        return authenticationResult.getAuthentication();
    }
182273
def get_issuer(self):
        
        issuer = None
        issuer_nodes = self.__query('/samlp:LogoutResponse/saml:Issuer')
        if len(issuer_nodes) == 1:
            issuer = OneLogin_Saml2_Utils.element_text(issuer_nodes[0])
        return issuer
431256
def _make_authorization_grant_assertion(self):
        
        now = _helpers.utcnow()
        lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
        expiry = now + lifetime

        payload = {
            'iat': _helpers.datetime_to_secs(now),
            'exp': _helpers.datetime_to_secs(expiry),
            # The issuer must be the service account email.
            'iss': self._service_account_email,
            # The audience must be the auth token endpoint's URI
            'aud': self._token_uri,
            'scope': _helpers.scopes_to_string(self._scopes or ())
        }

        payload.update(self._additional_claims)

        # The subject can be a user email for domain-wide delegation.
        if self._subject:
            payload.setdefault('sub', self._subject)

        token = jwt.encode(self._signer, payload)

        return token
689644
protected void validateSignature(ConsumerAuthentication authentication) throws AuthenticationException {
    SignatureSecret secret = authentication.getConsumerDetails().getSignatureSecret();
    String token = authentication.getConsumerCredentials().getToken();
    OAuthProviderToken authToken = null;
    if (token != null && !"".equals(token)) {
      authToken = getTokenServices().getToken(token);
    }

    String signatureMethod = authentication.getConsumerCredentials().getSignatureMethod();
    OAuthSignatureMethod method;
    try {
      method = getSignatureMethodFactory().getSignatureMethod(signatureMethod, secret, authToken != null ? authToken.getSecret() : null);
    }
    catch (UnsupportedSignatureMethodException e) {
      throw new OAuthException(e.getMessage(), e);
    }

    String signatureBaseString = authentication.getConsumerCredentials().getSignatureBaseString();
    String signature = authentication.getConsumerCredentials().getSignature();
    if (log.isDebugEnabled()) {
      log.debug("Verifying signature " + signature + " for signature base string " + signatureBaseString + " with method " + method.getName() + ".");
    }
    method.verify(signatureBaseString, signature);
  }
531735
def certificate_issuer_id(self, certificate_issuer_id):
        
        if certificate_issuer_id is None:
            raise ValueError("Invalid value for `certificate_issuer_id`, must not be `None`")
        if certificate_issuer_id is not None and len(certificate_issuer_id) > 32:
            raise ValueError("Invalid value for `certificate_issuer_id`, length must be less than or equal to `32`")

        self._certificate_issuer_id = certificate_issuer_id
6517
private AuthnRequest createAuthRequest(SamlIdentityProviderConfig idp, String defaultHostname) {
        requireNonNull(idp, "idp");

        final AuthnRequest authnRequest = build(AuthnRequest.DEFAULT_ELEMENT_NAME);

        final Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME);
        issuer.setValue(myEntityId);
        authnRequest.setIssuer(issuer);

        authnRequest.setIssueInstant(DateTime.now());
        authnRequest.setDestination(idp.ssoEndpoint().toUriString());
        authnRequest.setID(requestIdManager.newId());

        // The ProtocolBinding attribute is mutually exclusive with the AssertionConsumerServiceIndex attribute
        // and is typically accompanied by the AssertionConsumerServiceURL attribute.
        final SamlPortConfig portConfig = portConfigHolder.config().get();
        final SamlEndpoint acsEndpoint = idp.acsEndpoint()
                                            .orElse(sp.defaultAcsConfig().endpoint());
        authnRequest.setAssertionConsumerServiceURL(acsEndpoint.toUriString(portConfig.scheme().uriText(),
                                                                            defaultHostname,
                                                                            portConfig.port()));
        authnRequest.setProtocolBinding(acsEndpoint.bindingProtocol().urn());

        final SamlNameIdPolicy policy = idp.nameIdPolicy();
        final NameIDPolicy nameIdPolicy = build(NameIDPolicy.DEFAULT_ELEMENT_NAME);
        nameIdPolicy.setFormat(policy.format().urn());
        nameIdPolicy.setAllowCreate(policy.isCreatable());
        authnRequest.setNameIDPolicy(nameIdPolicy);

        final AuthnContextClassRef passwordAuthnCtxRef = build(AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
        passwordAuthnCtxRef.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX);

        final RequestedAuthnContext requestedAuthnContext = build(RequestedAuthnContext.DEFAULT_ELEMENT_NAME);
        requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
        requestedAuthnContext.getAuthnContextClassRefs().add(passwordAuthnCtxRef);

        authnRequest.setRequestedAuthnContext(requestedAuthnContext);

        return authnRequest;
    }