Should sign token for service?

@param svc the svc
@return the boolean
513250
@Override
    protected boolean shouldSignTokenFor(final OidcRegisteredService svc) {
        if (AlgorithmIdentifiers.NONE.equalsIgnoreCase(svc.getIdTokenSigningAlg())) {
            LOGGER.warn("ID token signing algorithm is set to none for [{}] and ID token will not be signed", svc.getServiceId());
            return false;
        }
        return svc.isSignIdToken();
    }
10394
public static boolean isSelfSigned(X509Certificate cert,
        String sigProvider) {
        if (isSelfIssued(cert)) {
            try {
                if (sigProvider == null) {
                    cert.verify(cert.getPublicKey());
                } else {
                    cert.verify(cert.getPublicKey(), sigProvider);
                }
                return true;
            } catch (Exception e) {
                // In case of exception, return false
            }
        }
        return false;
    }
1207385
function(callback) {
        if (!res.parsedHeader.signature) {
          callback('unsigned');
        } else {
          var signVerifier = new Crypter({
            cert: res.session.cert
          });
          if (signVerifier.verifySignature(JSON.stringify(res.parsedHeader.content), res.parsedHeader.signature)) {
            callback(null);
          } else {
            callback('forgery');
          }
        }
      }
75064
protected String urlDecodeSignedRequestToken(String signedRequestToken) {
    verifyParameterPresence("signedRequestToken", signedRequestToken);
    return signedRequestToken.replace("-", "+").replace("_", "/").trim();
  }
854448
public static boolean isValidSignature(HttpServletRequest incoming, String secretKey) {
		if (incoming == null || StringUtils.isBlank(secretKey)) {
			return false;
		}
		String auth = incoming.getHeader(HttpHeaders.AUTHORIZATION);
		String givenSig = StringUtils.substringAfter(auth, "Signature=");
		String sigHeaders = StringUtils.substringBetween(auth, "SignedHeaders=", ",");
		String credential = StringUtils.substringBetween(auth, "Credential=", ",");
		String accessKey = StringUtils.substringBefore(credential, "/");

		if (StringUtils.isBlank(auth)) {
			givenSig = incoming.getParameter("X-Amz-Signature");
			sigHeaders = incoming.getParameter("X-Amz-SignedHeaders");
			credential = incoming.getParameter("X-Amz-Credential");
			accessKey = StringUtils.substringBefore(credential, "/");
		}

		Set<String> headersUsed = new HashSet<>(Arrays.asList(sigHeaders.split(";")));
		Map<String, String> headers = new HashMap<>();
		for (Enumeration<String> e = incoming.getHeaderNames(); e.hasMoreElements();) {
			String head = e.nextElement().toLowerCase();
			if (headersUsed.contains(head)) {
				headers.put(head, incoming.getHeader(head));
			}
		}

		Map<String, String> params = new HashMap<>();
		for (Map.Entry<String, String[]> param : incoming.getParameterMap().entrySet()) {
			params.put(param.getKey(), param.getValue()[0]);
		}

		String path = incoming.getRequestURI();
		String endpoint = StringUtils.removeEndIgnoreCase(incoming.getRequestURL().toString(), path);
		String httpMethod = incoming.getMethod();
		InputStream entity;
		try {
			entity = new BufferedRequestWrapper(incoming).getInputStream();
			if (entity.available() <= 0) {
				entity = null;
			}
		} catch (IOException ex) {
			logger.error(null, ex);
			entity = null;
		}

		Signer signer = new Signer();
		Map<String, String> sig = signer.sign(httpMethod, endpoint, path, headers, params, entity, accessKey, secretKey);

		String auth2 = sig.get(HttpHeaders.AUTHORIZATION);
		String recreatedSig = StringUtils.substringAfter(auth2, "Signature=");

		return StringUtils.equals(givenSig, recreatedSig);
	}
1100619
@Override
    protected boolean shouldEncryptTokenFor(final OidcRegisteredService svc) {
        if (AlgorithmIdentifiers.NONE.equalsIgnoreCase(svc.getIdTokenEncryptionAlg())) {
            LOGGER.warn("ID token encryption algorithm is set to none for [{}] and ID token will not be encrypted", svc.getServiceId());
            return false;
        }
        return svc.isEncryptIdToken() && StringUtils.isNotBlank(svc.getIdTokenEncryptionAlg()) && StringUtils.isNotBlank(svc.getIdTokenEncryptionEncoding());
    }
697284
static void sign(SignableSAMLObject signableObj, Credential signingCredential, String signatureAlgorithm) {
        requireNonNull(signableObj, "signableObj");
        requireNonNull(signingCredential, "signingCredential");
        requireNonNull(signatureAlgorithm, "signatureAlgorithm");

        final Signature signature = signatureBuilder.buildObject();
        signature.setSignatureAlgorithm(signatureAlgorithm);
        signature.setSigningCredential(signingCredential);
        signature.setCanonicalizationAlgorithm(ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        try {
            signature.setKeyInfo(keyInfoGenerator.generate(signingCredential));
        } catch (SecurityException e) {
            throw new SamlException("failed to create a key info of signing credential", e);
        }

        signableObj.setSignature(signature);
        serialize(signableObj);

        try {
            Signer.signObject(signature);
        } catch (SignatureException e) {
            throw new SamlException("failed to sign a SAML object", e);
        }
    }
434577
protected SignatureSigningConfiguration getSignatureSigningConfiguration(final RoleDescriptor roleDescriptor,
                                                                             final SamlRegisteredService service) throws Exception {
        val config = DefaultSecurityConfigurationBootstrap.buildDefaultSignatureSigningConfiguration();
        val samlIdp = casProperties.getAuthn().getSamlIdp();
        val algs = samlIdp.getAlgs();

        val overrideSignatureReferenceDigestMethods = algs.getOverrideSignatureReferenceDigestMethods();
        val overrideSignatureAlgorithms = algs.getOverrideSignatureAlgorithms();
        val overrideBlackListedSignatureAlgorithms = algs.getOverrideBlackListedSignatureSigningAlgorithms();
        val overrideWhiteListedAlgorithms = algs.getOverrideWhiteListedSignatureSigningAlgorithms();

        if (overrideBlackListedSignatureAlgorithms != null && !overrideBlackListedSignatureAlgorithms.isEmpty()) {
            config.setBlacklistedAlgorithms(overrideBlackListedSignatureAlgorithms);
        }

        if (overrideSignatureAlgorithms != null && !overrideSignatureAlgorithms.isEmpty()) {
            config.setSignatureAlgorithms(overrideSignatureAlgorithms);
        }

        if (overrideSignatureReferenceDigestMethods != null && !overrideSignatureReferenceDigestMethods.isEmpty()) {
            config.setSignatureReferenceDigestMethods(overrideSignatureReferenceDigestMethods);
        }

        if (overrideWhiteListedAlgorithms != null && !overrideWhiteListedAlgorithms.isEmpty()) {
            config.setWhitelistedAlgorithms(overrideWhiteListedAlgorithms);
        }

        if (StringUtils.isNotBlank(algs.getOverrideSignatureCanonicalizationAlgorithm())) {
            config.setSignatureCanonicalizationAlgorithm(algs.getOverrideSignatureCanonicalizationAlgorithm());
        }
        LOGGER.trace("Signature signing blacklisted algorithms: [{}]", config.getBlacklistedAlgorithms());
        LOGGER.trace("Signature signing signature algorithms: [{}]", config.getSignatureAlgorithms());
        LOGGER.trace("Signature signing signature canonicalization algorithm: [{}]", config.getSignatureCanonicalizationAlgorithm());
        LOGGER.trace("Signature signing whitelisted algorithms: [{}]", config.getWhitelistedAlgorithms());
        LOGGER.trace("Signature signing reference digest methods: [{}]", config.getSignatureReferenceDigestMethods());

        val privateKey = getSigningPrivateKey();

        val kekCredentialResolver = new MetadataCredentialResolver();
        val roleDescriptorResolver = SamlIdPUtils.getRoleDescriptorResolver(casSamlIdPMetadataResolver, samlIdp.getMetadata().isRequireValidMetadata());
        kekCredentialResolver.setRoleDescriptorResolver(roleDescriptorResolver);
        kekCredentialResolver.setKeyInfoCredentialResolver(DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver());
        kekCredentialResolver.initialize();
        
        val criteriaSet = new CriteriaSet();
        criteriaSet.add(new SignatureSigningConfigurationCriterion(config));
        criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
        criteriaSet.add(new EntityIdCriterion(samlIdp.getEntityId()));
        criteriaSet.add(new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME));

        val credentials = Sets.<Credential>newLinkedHashSet(kekCredentialResolver.resolve(criteriaSet));
        val creds = new ArrayList<Credential>();

        credentials.forEach(c -> {
            val cred = getResolvedSigningCredential(c, privateKey, service);
            if (cred != null) {
                if (doesCredentialFingerprintMatch(cred, service)) {
                    creds.add(cred);
                }
            }
        });

        if (creds.isEmpty()) {
            LOGGER.error("Unable to locate any signing credentials for service [{}]", service.getName());
            throw new IllegalArgumentException("Unable to locate signing credentials");
        }

        config.setSigningCredentials(creds);
        LOGGER.trace("Signature signing credentials configured with [{}] credentials", creds.size());
        return config;
    }
1243146
private boolean hasAuthenticatedMolgenisToken() {
    boolean hasAuthenticatedMolgenisToken = false;
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof RestAuthenticationToken) {
      hasAuthenticatedMolgenisToken = authentication.isAuthenticated();
    }
    return hasAuthenticatedMolgenisToken;
  }
127897
public function validateRequestToken(TokenRequest $requestToken, $certificate = null)
    {
        if (empty($requestToken->getIssuer()) || empty($requestToken->getSignature())) {
            return false;
        }

        if (!is_null($certificate)) {
            return $this->verifySignature($requestToken, $certificate);
        }

        return true;
    }
664644
public KeyOperationResult sign(String keyIdentifier, JsonWebKeySignatureAlgorithm algorithm, byte[] value) {
        KeyIdentifier id = new KeyIdentifier(keyIdentifier);
        return sign(id.vault(), id.name(), id.version() == null ? "" : id.version(), algorithm, value);
    }
38572
public static final void signAuthToken(AuthToken token) {
        String signature = generateSignature(token);
        token.setSignature(signature);
    }
864491
@Override
    public boolean supports(AuthenticationToken token) {
        return super.supports(token) || (_anonymousId != null && AnonymousToken.isAnonymous(token));
    }
327263
public boolean validateSignature(final Pair<Assertion, WsFederationConfiguration> resultPair) {
        if (resultPair == null) {
            LOGGER.warn("No assertion or its configuration was provided to validate signatures");
            return false;
        }
        val configuration = resultPair.getValue();
        val assertion = resultPair.getKey();

        if (assertion == null || configuration == null) {
            LOGGER.warn("No signature or configuration was provided to validate signatures");
            return false;
        }
        val signature = assertion.getSignature();
        if (signature == null) {
            LOGGER.warn("No signature is attached to the assertion to validate");
            return false;
        }

        try {
            LOGGER.debug("Validating the signature...");
            val validator = new SAMLSignatureProfileValidator();
            validator.validate(signature);

            val criteriaSet = new CriteriaSet();
            criteriaSet.add(new UsageCriterion(UsageType.SIGNING));
            criteriaSet.add(new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME));
            criteriaSet.add(new ProtocolCriterion(SAMLConstants.SAML20P_NS));
            criteriaSet.add(new EntityIdCriterion(configuration.getIdentityProviderIdentifier()));
            try {
                val engine = buildSignatureTrustEngine(configuration);
                LOGGER.debug("Validating signature via trust engine for [{}]", configuration.getIdentityProviderIdentifier());
                return engine.validate(signature, criteriaSet);
            } catch (final SecurityException e) {
                LOGGER.warn(e.getMessage(), e);
            }
        } catch (final SignatureException e) {
            LOGGER.error("Failed to validate assertion signature", e);
        }

        SamlUtils.logSamlObject(this.configBean, assertion);

        LOGGER.error("Signature doesn't match any signing credential and cannot be validated.");
        return false;
    }
938240
public boolean authenticate(AuthToken token, Message msg) {
        if ((token != null) && (token instanceof FixedMembershipToken) && (this.memberList != null)) {
            PhysicalAddress src = (PhysicalAddress) auth.down(new Event(Event.GET_PHYSICAL_ADDRESS, msg.getSrc()));
            if (src == null) {
                log.error(Util.getMessage("DidnTFindPhysicalAddressFor") + msg.getSrc());
                return false;
            }
            return isInMembersList((IpAddress)src);
        }

        if (log.isWarnEnabled())
            log.warn("Invalid AuthToken instance - wrong type or null");
        return false;
    }
38453
protected String signToken(final OidcRegisteredService svc, final JsonWebSignature jws) throws Exception {
        LOGGER.debug("Fetching JSON web key to sign the token for : [{}]", svc.getClientId());
        val jsonWebKey = getJsonWebKeySigningKey();
        LOGGER.debug("Found JSON web key to sign the token: [{}]", jsonWebKey);
        if (jsonWebKey.getPrivateKey() == null) {
            throw new IllegalArgumentException("JSON web key used to sign the token has no associated private key");
        }
        configureJsonWebSignatureForTokenSigning(svc, jws, jsonWebKey);
        return jws.getCompactSerialization();
    }
427769
private void assertIsFromSns(URI certUrl) {
        if (!endpoint.equals(certUrl.getHost())) {
            throw new SdkClientException(
                String.format("SigningCertUrl does not match expected endpoint. Expected %s but received endpoint was %s.",
                              endpoint, certUrl.getHost()));

        }
    }