Verifies a received SAD request.

@param sadRequest
the request to verify
@param context
the context
@throws ExternalAutenticationErrorCodeException
for errors
766948
protected void verifySadRequest(SignatureActivationDataContext sadRequest, ProfileRequestContext<?, ?> context)
      throws ExternalAutenticationErrorCodeException {

    final AuthnRequest authnRequest = this.getAuthnRequest(context);
    if (authnRequest == null) {
      log.error("No AuthnRequest available [{}]", this.getLogString(context));
      throw new ExternalAutenticationErrorCodeException(AuthnEventIds.INVALID_AUTHN_CTX, "Missing AuthnRequest");
    }

    final SADRequest r = sadRequest.getSadRequest();

    // Verify the version is what we understand ...
    //
    if (r.getRequestedVersion() != null && !supportedSadVersions.contains(r.getRequestedVersion())) {
      final String msg = String.format("Requested SAD version (%s) is not supported by the IdP", r.getRequestedVersion());
      log.info("{} [{}]", msg, this.getLogString(context));
      throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.BAD_SAD_REQUEST, msg);
    }

    // Check the RequesterID ...
    //
    if (!StringUtils.hasText(r.getRequesterID())) {
      final String msg = "RequesterID is not present in the SADRequest - invalid";
      log.info("{} [{}]", msg, this.getLogString(context));
      throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.BAD_SAD_REQUEST, msg);
    }
    final String issuer = authnRequest.getIssuer().getValue();
    if (!r.getRequesterID().equals(issuer)) {
      final String msg = String.format("Invalid RequestID of SADRequest (%s) - Issuer of AuthnRequest is '%s'", r.getRequesterID(), issuer);
      log.info("{} [{}]", msg, this.getLogString(context));
      throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.BAD_SAD_REQUEST, msg);
    }

    // Verify that the SignRequestID is there ...
    //
    if (!StringUtils.hasText(r.getSignRequestID())) {
      final String msg = "SignRequestID is not present in the SADRequest - invalid";
      log.info("{} [{}]", msg, this.getLogString(context));
      throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.BAD_SAD_REQUEST, msg);
    }

    // Assert that we have a DocCount element ...
    //
    if (r.getDocCount() == null) {
      final String msg = "DocCount is not present in the SADRequest - invalid";
      log.info("{} [{}]", msg, this.getLogString(context));
      throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.BAD_SAD_REQUEST, msg);
    }

    // Assert that we have an ID for the SADRequest ...
    //
    if (!StringUtils.hasText(r.getID())) {
      final String msg = "ID attribute is not present in the SADRequest - invalid";
      log.info("{} [{}]", msg, this.getLogString(context));
      throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.BAD_SAD_REQUEST, msg);
    }
  }
122174
protected void viaLastaDiContext(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        final LaContainer container = SingletonLaContainerFactory.getContainer();
        final ExternalContext externalContext = container.getExternalContext();
        if (externalContext == null) {
            throw new IllegalStateException("The externalContext should not be null from the container: " + container);
        }
        final Object prevoiusRequest = externalContext.getRequest();
        final Object previousResponse = externalContext.getResponse();
        try {
            externalContext.setRequest(request);
            externalContext.setResponse(response);
            viaHotdeploy(request, response, chain); // #to_action
        } finally {
            externalContext.setRequest(prevoiusRequest);
            externalContext.setResponse(previousResponse);
        }
    }
1093916
public void notifyObserversOfRequestFailure(CachedSpiceRequest<?> request) {
        RequestProcessingContext requestProcessingContext = new RequestProcessingContext();
        requestProcessingContext.setExecutionThread(Thread.currentThread());
        post(new RequestFailedNotifier(request, spiceServiceListenerList, requestProcessingContext));
    }
1225166
protected HttpServletRequest getServletRequestFromExternalContext(
            ExternalContext externalContext) {
        Object request = externalContext.getNativeRequest();

        if (request instanceof PortletRequest) {
            return portalRequestUtils.getPortletHttpRequest(
                    (PortletRequest) externalContext.getNativeRequest());
        } else if (request instanceof HttpServletRequest) {
            return (HttpServletRequest) request;
        }

        // give up and throw an error
        else {
            throw new IllegalArgumentException(
                    "Unable to recognize the native request associated with the supplied external context");
        }
    }
1044735
protected static void requestAuthenticated(final Request request) {
        if (null == request) {
            return;
        }

        if (!WonderPush.isInitialized()) {
            WonderPush.safeDefer(new Runnable() {
                @Override
                public void run() {
                    requestAuthenticated(request);
                }
            }, 100);
            return;
        }

        String accessToken = WonderPushConfiguration.getAccessTokenForUserId(request.getUserId());

        if (accessToken == null) {
            // User is not authenticated, request a token
            fetchAnonymousAccessTokenAndRunRequest(request);
            return;
        }

        // Add the access token to the params
        RequestParams params = request.getParams();
        if (null == params) {
            params = new RequestParams();
            request.setParams(params);
        }

        params.remove("accessToken");
        params.put("accessToken", accessToken);

        // Wrap the request handler with our own
        ResponseHandler wrapperHandler = new ResponseHandler() {
            @Override
            public void onSuccess(int status, Response response) {
                WonderPush.logDebug("Request successful: (" + status + ") " + response + " (for " + request + ")");
                if (request.getHandler() != null) {
                    request.getHandler().onSuccess(status, response);
                }
            }

            @Override
            public void onFailure(Throwable e, Response errorResponse) {
                WonderPush.logError("Request failed: " + errorResponse, e);
                if (errorResponse != null && ERROR_INVALID_ACCESS_TOKEN == errorResponse.getErrorCode()) {
                    // null out the access token
                    WonderPushConfiguration.invalidateCredentials();

                    // retry later now
                    WonderPush.safeDefer(new Runnable() {
                        @Override
                        public void run() {
                            requestAuthenticated(request);
                        }
                    }, RETRY_INTERVAL_BAD_AUTH);
                } else {
                    if (request.getHandler() != null) {
                        request.getHandler().onFailure(e, errorResponse);
                    }
                }
            }

            @Override
            public void onSuccess(Response response) {
                WonderPush.logDebug("Request successful: " + response + " (for " + request + ")");
                if (request.getHandler() != null) {
                    request.getHandler().onSuccess(response);
                }
            }
        };
        Request wrapperRequest = (Request) request.clone();
        wrapperRequest.setHandler(wrapperHandler);

        // Perform request
        request(wrapperRequest);
    }
1351555
public static boolean validateTokenRequest(TokenRequestDto tokenRequestDto, OAuthApplicationDto oAuthApplicationDto) {
        // basic check
        try {
            String decodedRedirectUri = java.net.URLDecoder.decode(tokenRequestDto.getRedirectUri(), "UTF-8");
            if (StringUtils.isNotBlank(oAuthApplicationDto.getRedirectUri()) && oAuthApplicationDto.getRedirectUri().equals(decodedRedirectUri)) {
                if (StringUtils.isNotBlank(tokenRequestDto.getGrantType())) {
                    if (OAuthFields.AUTHORIZATION_CODE.equals(tokenRequestDto.getGrantType())) {
                        return true;
                    } else {
                        _logger.info("Grant Type '" + tokenRequestDto.getGrantType() + "' is not supported");
                        throw new OAuthException(ResponseCodes.GRANT_TYPE_NOT_SUPPORTED, HttpResponseStatus.BAD_REQUEST);
                    }
                } else {
                    _logger.info("Grant Type '" + tokenRequestDto.getGrantType() + "' mismatch");
                    throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_GRANT_TYPE, HttpResponseStatus.BAD_REQUEST);
                }
            } else {
                _logger.info("Request Redirect URI '" + tokenRequestDto.getRedirectUri() + "' mismatch");
                throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST);
            }
        } catch (UnsupportedEncodingException e) {
            _logger.info("Request Redirect URI '" + tokenRequestDto.getRedirectUri() + "' mismatch");
            throw new OAuthException(ResponseCodes.INVALID_OR_MISSING_REDIRECT_URI, HttpResponseStatus.BAD_REQUEST);
        }

    }
1010029
public synchronized void onRequestFailed(Throwable reason) {
		allRequestsTracker.onRequestFailed(reason);
		recentRequestsTracker.onRequestFailed(reason);
		meter.mark();
	}
277979
protected void handleAccessDeniedException(RequestContext context, AccessDeniedException e) throws
            SecurityProviderException, IOException {
        Authentication auth = SecurityUtils.getAuthentication(context.getRequest());
        // If user is anonymous, authentication is required
        if (auth == null) {
            try {
                // Throw ex just to initialize stack trace
                throw new AuthenticationRequiredException("Authentication required to access the resource", e);
            } catch (AuthenticationRequiredException ae) {
                logger.debug("Authentication is required", ae);

                authenticationRequiredHandler.handle(context, ae);
            }
        } else {
            logger.debug("Access denied to user '" + auth.getProfile().getUsername() + "'", e);

            accessDeniedHandler.handle(context, e);
        }
    }
122460
public synchronized void onRequestFailed(String reason) {
		allRequestsTracker.onRequestFailed(reason);
		recentRequestsTracker.onRequestFailed(reason);
		meter.mark();
	}
1140662
@Override
  public boolean failedSendRecord(ClientAccSession appSession, Request accRequest) throws InternalException {
    logger.info("failedSendRecord :: appSession[" + appSession + "], Request[" + accRequest + "]");
    return false;
  }
730563
public void validateAttributesForm(
            AttributeSwapRequest attributeSwapRequest, MessageContext context) {
        final RequestContext requestContext = RequestContextHolder.getRequestContext();
        final ExternalContext externalContext = requestContext.getExternalContext();
        final Set<String> swappableAttributes =
                this.attributeSwapperHelper.getSwappableAttributes(externalContext);

        final Map<String, Attribute> currentAttributes =
                attributeSwapRequest.getCurrentAttributes();
        this.checkAttributesMap(
                context, "currentAttributes", swappableAttributes, currentAttributes);

        final Map<String, Attribute> attributesToCopy = attributeSwapRequest.getAttributesToCopy();
        this.checkAttributesMap(context, "attributesToCopy", swappableAttributes, attributesToCopy);
    }
328933
@Override
  public void processRequest(ProfileRequestContext<?, ?> context) throws ExternalAutenticationErrorCodeException {

    final String logId = this.getLogString(context);
    boolean isSignatureService = this.isSignatureServicePeer(context);

    SignMessageContext signMessageContext = this.getSignMessageContext(context);
    if (signMessageContext == null) {

      // If the peer is a signature service and has only requested a sigmessage LoA we report an error.
      //
      if (isSignatureService) {
        AuthnContextClassContext authnContextClassContext = this.authnContextService.getAuthnContextClassContext(context);
        for (String loa : authnContextClassContext.getAuthnContextClassRefs()) {
          if (this.isSignMessageURI(loa)) {
            log.info("SP has requested '{}' but did not include SignMessage, removing ... [{}]", loa, logId);
            authnContextClassContext.deleteAuthnContextClassRef(loa);
          }
        }
        if (authnContextClassContext.isEmpty()) {
          final String msg = "No valid AuthnContext URI:s were specified in AuthnRequest";
          log.info("{} - can not proceed [{}]", msg, logId);
          throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, msg);
        }
      }
    }
    else {
      // If an ordinary SP included a SignMessage in the request, we simply ignore it.
      //
      if (!isSignatureService) {
        log.warn("Requesting SP is not a signature service, but included SignMessage extension, ignoring ... [{}]", logId);
        AuthenticationContext authnContext = authenticationContextLookupStrategy.apply(context);
        if (authnContext == null) {
          log.error("No AuthenticationContext available [{}]", this.getLogString(context));
          throw new ExternalAutenticationErrorCodeException(AuthnEventIds.INVALID_AUTHN_CTX, "Missing AuthenticationContext");
        }
        authnContext.removeSubcontext(SignMessageContext.class);
      }
      // Else, make additional checks and decrypt.
      //
      else {

        // Decrypt the message
        //
        if (signMessageContext.getSignMessage().getEncryptedMessage() != null) {
          try {
            Message cleartextMessage = this.signatureSupportKeyService.decrypt(signMessageContext.getSignMessage());
            log.debug("SignMessage was successfully decrypted [{}]", logId);
            signMessageContext.setClearTextMessage(cleartextMessage);
          }
          catch (DecryptionException e) {
            final String msg = String.format("Failed to decrypt SignMessage - %s", e.getMessage());
            log.error("{} [{}]", msg, logId);
            throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SIGN_MESSAGE_DECRYPTION_ERROR, msg);
          }
        }
        else {
          log.debug("SignMessage was not encrypted [{}]", logId);
        }

        if (!this.supportsMimeType(signMessageContext.getMimeType())) {
          log.warn("IdP does not support display of SignMessage with type '{}' [{}]", signMessageContext.getMimeType(), logId);
          signMessageContext.setDoDisplayMessage(false);

          if (signMessageContext.mustShow()) {
            throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SIGN_MESSAGE_TYPE_NOT_SUPPORTED,
              "Unsupported SignMessage mime type");
          }
        }
        // If the SignMessage element from the signature request includes a MustShow attribute with the value true, the
        // Signature Service MUST require that the provided sign message is displayed by the Identity Provider, by
        // including a sigmessage authentication context URI.
        //
        if (signMessageContext.mustShow()) {
          AuthnContextClassContext authnContextClassContext = this.authnContextService.getAuthnContextClassContext(context);
          for (String loa : authnContextClassContext.getAuthnContextClassRefs()) {
            if (!this.isSignMessageURI(loa)) {
              log.info("SP has requested the SignMessage must be displayed, removing '{}' ... [{}]", loa, logId);
              authnContextClassContext.deleteAuthnContextClassRef(loa);
            }
          }
          if (authnContextClassContext.isEmpty()) {
            final String msg = "No valid sigmessage AuthnContext URI:s were specified in AuthnRequest";
            log.info("{} - can not proceed [{}]", msg, logId);
            throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, msg);
          }
        }

        signMessageContext.setDoDisplayMessage(true);
      }
    }

  }
549651
private boolean validateAssertion(final HttpServletRequest request, final String serviceTicketId, final Assertion assertion, final Service service) {
        for (val spec : serviceValidateConfigurationContext.getValidationSpecifications()) {
            spec.reset();
            val binder = new ServletRequestDataBinder(spec, "validationSpecification");
            initBinder(request, binder);
            binder.bind(request);
            if (!spec.isSatisfiedBy(assertion, request)) {
                LOGGER.warn("Service ticket [{}] does not satisfy validation specification.", serviceTicketId);
                return false;
            }
        }
        enforceTicketValidationAuthorizationFor(request, service, assertion);
        return true;
    }
1315238
protected AuthenticationContext getAuthenticationContext(ProfileRequestContext<?, ?> context)
      throws ExternalAutenticationErrorCodeException {
    AuthenticationContext authnContext = authenticationContextLookupStrategy.apply(context);
    if (authnContext == null) {
      log.error("No AuthenticationContext available [{}]", this.getLogString(context));
      throw new ExternalAutenticationErrorCodeException(AuthnEventIds.INVALID_AUTHN_CTX, "Missing AuthenticationContext");
    }
    return authnContext;
  }
1146373
private void executeValidate(FacesContext context) {
        try {
            validate(context);
        } catch (RuntimeException e) {
            context.renderResponse();
            throw e;
        }

        if (!isValid()) {
            context.validationFailed();
            context.renderResponse();
        }
    }
631348
public void validate(final ValidationContext context) {
        if (!isValid()) {
            val messages = context.getMessageContext();
            messages.addMessage(new MessageBuilder()
                .error()
                .source("token")
                .defaultText("Unable to accept credential with an empty or unspecified token")
                .build());
        }
    }
176741
protected ProfileRequestContext<?, ?> getProfileRequestContext(HttpServletRequest httpRequest) throws ExternalAuthenticationException {
    return ExternalAuthentication.getProfileRequestContext(this.getExternalAuthenticationKey(httpRequest), httpRequest);
  }