Calculate score authentication risk score.

@param request        the request
@param authentication the authentication
@param service        the service
@param events         the events
@return the authentication risk score
5073
protected BigDecimal calculateScore(final HttpServletRequest request,
                                        final Authentication authentication,
                                        final RegisteredService service,
                                        final Collection<? extends CasEvent> events) {
        return HIGHEST_RISK_SCORE;
    }
513803
@Override
    public AuthenticationStatus authenticate(HttpServletRequest req, HttpServletResponse res, AuthenticationParameters params) {
        AuthenticationStatus authStatus = AuthenticationStatus.SEND_FAILURE;
        req.setAttribute(JavaEESecConstants.SECURITY_CONTEXT_AUTH_PARAMS, params);
        try {
            boolean result = req.authenticate(res);
            if (result) {
                authStatus = AuthenticationStatus.SUCCESS;
            } else {
//TODO some error handling.
            }
        } catch (Exception e) {
//TODO need to handle error.
            e.printStackTrace();
        }
        return authStatus;
    }
452130
public static void httpComponentWithTry(HttpPut request, String auth) {
        auth = auth + "password";
        try {
            // this will probably be tagged with
            // CSI_CHAR_SET_ISSUES_USE_STANDARD_CHARSET, if compiled under JDK 7
            // or later
            request.addHeader("Authorization", Base64.encodeBase64String(auth.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
1154974
public boolean authenticate(HttpServletRequest request) throws MnoException {
		String authHeader = request.getHeader("Authorization");
		if (authHeader == null || authHeader.isEmpty()) {
			return false;
		}
		String[] auth = authHeader.trim().split("\\s+");

		if (auth == null || auth.length != 2 || !auth[0].equalsIgnoreCase("basic")) {
			return false;
		}
		byte[] decodedStr = DatatypeConverter.parseBase64Binary(auth[1]);
		String[] creds;
		try {
			creds = (new String(decodedStr, "UTF-8")).split(":");
		} catch (UnsupportedEncodingException e) {
			throw new MnoException("Could not decode basic authentication" + Arrays.toString(auth), e);
		}

		if (creds.length == 2) {
			return authenticate(creds[0], creds[1]);
		} else {
			return false;
		}
	}
835436
protected ModelAndView handleTicketValidation(final HttpServletRequest request, final WebApplicationService service, final String serviceTicketId) {
        var proxyGrantingTicketId = (TicketGrantingTicket) null;
        val serviceCredential = getServiceCredentialsFromRequest(service, request);
        if (serviceCredential != null) {
            try {
                proxyGrantingTicketId = handleProxyGrantingTicketDelivery(serviceTicketId, serviceCredential);
            } catch (final AuthenticationException e) {
                LOGGER.warn("Failed to authenticate service credential [{}]", serviceCredential);
                return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_PROXY_CALLBACK, new Object[]{serviceCredential.getId()}, request, service);
            } catch (final InvalidTicketException e) {
                LOGGER.error("Failed to create proxy granting ticket due to an invalid ticket for [{}]", serviceCredential, e);
                return generateErrorView(e.getCode(), new Object[]{serviceTicketId}, request, service);
            } catch (final AbstractTicketException e) {
                LOGGER.error("Failed to create proxy granting ticket for [{}]", serviceCredential, e);
                return generateErrorView(e.getCode(), new Object[]{serviceCredential.getId()}, request, service);
            }
        }
        val assertion = validateServiceTicket(service, serviceTicketId);
        if (!validateAssertion(request, serviceTicketId, assertion, service)) {
            return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_TICKET, new Object[]{serviceTicketId}, request, service);
        }

        val ctxResult = serviceValidateConfigurationContext.getRequestedContextValidator().validateAuthenticationContext(assertion, request);
        if (!ctxResult.getKey()) {
            throw new UnsatisfiedAuthenticationContextTicketValidationException(assertion.getService());
        }

        var proxyIou = StringUtils.EMPTY;
        val proxyHandler = serviceValidateConfigurationContext.getProxyHandler();
        if (serviceCredential != null && proxyHandler != null && proxyHandler.canHandle(serviceCredential)) {
            proxyIou = handleProxyIouDelivery(serviceCredential, proxyGrantingTicketId);
            if (StringUtils.isEmpty(proxyIou)) {
                return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_PROXY_CALLBACK, new Object[]{serviceCredential.getId()}, request, service);
            }
        } else {
            LOGGER.debug("No service credentials specified, and/or the proxy handler [{}] cannot handle credentials", proxyHandler);
        }
        onSuccessfulValidation(serviceTicketId, assertion);
        LOGGER.debug("Successfully validated service ticket [{}] for service [{}]", serviceTicketId, service.getId());
        return generateSuccessView(assertion, proxyIou, service, request, ctxResult.getValue(), proxyGrantingTicketId);
    }
595503
protected BigDecimal calculateScoreBasedOnEventsCount(final Authentication authentication,
                                                          final Collection<? extends CasEvent> events,
                                                          final long count) {
        if (count == events.size()) {
            LOGGER.debug("Principal [{}] is assigned to the lowest risk score with attempted count of [{}]", authentication.getPrincipal(), count);
            return LOWEST_RISK_SCORE;
        }
        return getFinalAveragedScore(count, events.size());
    }
1088627
void sign(HttpRequest request, AuthConfig credentials, Date signingTime) {
        AwsSigner4Request sr = new AwsSigner4Request(region, service, request, signingTime);
        if(!request.containsHeader("X-Amz-Date")) {
            request.addHeader("X-Amz-Date", sr.getSigningDateTime());
        }
        request.addHeader("Authorization", task4(sr, credentials));
        final String securityToken = credentials.getAuth();
        if (StringUtils.isNotEmpty(securityToken)) {
            request.addHeader("X-Amz-Security-Token", securityToken);
        }
    }
591333
public static void putAuthentication(final Authentication authentication, final RequestContext ctx) {
        ctx.getConversationScope().put(PARAMETER_AUTHENTICATION, authentication);
    }
823541
protected List<String> resolveEventFromHttpRequest(final HttpServletRequest request) {
        val mfaRequestHeader = casProperties.getAuthn().getMfa().getRequestHeader();
        val headers = request.getHeaders(mfaRequestHeader);
        if (headers != null && headers.hasMoreElements()) {
            LOGGER.debug("Received request header [{}] as [{}]", mfaRequestHeader, headers);
            return Collections.list(headers);
        }

        val mfaRequestParameter = casProperties.getAuthn().getMfa().getRequestParameter();
        val params = request.getParameterValues(mfaRequestParameter);
        if (params != null && params.length > 0) {
            LOGGER.debug("Received request parameter [{}] as [{}]", mfaRequestParameter, params);
            return Arrays.stream(params).collect(Collectors.toList());
        }

        val attributeName = casProperties.getAuthn().getMfa().getSessionAttribute();
        val session = request.getSession(false);
        var attributeValue = session != null ? session.getAttribute(attributeName) : null;
        if (attributeValue == null) {
            LOGGER.trace("No value could be found for session attribute [{}]. Checking request attributes...", attributeName);
            attributeValue = request.getAttribute(attributeName);
        }

        if (attributeValue == null) {
            LOGGER.trace("No value could be found for [{}]", attributeName);
            return null;
        }

        val values = CollectionUtils.toCollection(attributeValue);
        LOGGER.debug("Found values [{}] mapped to attribute name [{}]", values, attributeName);
        return values.stream().map(Object::toString).collect(Collectors.toList());
    }
709006
protected TicketGrantingTicket createTicketGrantingTicketForRequest(final MultiValueMap<String, String> requestBody,
                                                                        final HttpServletRequest request) {
        val credential = this.credentialFactory.fromRequest(request, requestBody);
        if (credential == null || credential.isEmpty()) {
            throw new BadRestRequestException("No credentials are provided or extracted to authenticate the REST request");
        }
        val service = this.serviceFactory.createService(request);
        val authenticationResult =
            authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, credential);
        return centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
    }
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();
    }
1210001
protected boolean requestRequiresAuthentication(final HttpServletRequest request, final HttpServletResponse response) {
        val accessTokenRequest = isAccessTokenRequest(request, response);
        if (!accessTokenRequest) {
            val extractor = extractAccessTokenGrantRequest(request);
            if (extractor.isPresent()) {
                val ext = extractor.get();
                return ext.requestMustBeAuthenticated();
            }
        } else {
            val extractor = extractAccessTokenGrantRequest(request);
            if (extractor.isPresent()) {
                val ext = extractor.get();
                return ext.getResponseType() != OAuth20ResponseTypes.DEVICE_CODE;
            }
        }
        return false;
    }
743826
protected void verifyAuthenticationContextSignature(final MessageContext ctx,
                                                        final HttpServletRequest request,
                                                        final RequestAbstractType authnRequest,
                                                        final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws Exception {
        if (!SAMLBindingSupport.isMessageSigned(ctx)) {
            LOGGER.debug("The authentication context is not signed");
            if (adaptor.isAuthnRequestsSigned()) {
                LOGGER.error("Metadata for [{}] says authentication requests are signed, yet authentication request is not", adaptor.getEntityId());
                throw new SAMLException("AuthN request is not signed but should be");
            }
            LOGGER.debug("Authentication request is not signed, so there is no need to verify its signature.");
        } else {
            LOGGER.debug("The authentication context is signed; Proceeding to validate signatures...");
            samlProfileHandlerConfigurationContext.getSamlObjectSignatureValidator().verifySamlProfileRequestIfNeeded(authnRequest, adaptor, request, ctx);
        }
    }
435847
private ApiCallMonitoringEvent generateApiCallMonitoringEvent(Request<?> request) {
        String apiName = request.getHandlerContext(HandlerContextKey.OPERATION_NAME);
        String serviceId = request.getHandlerContext(HandlerContextKey.SERVICE_ID);
        String region = request.getHandlerContext(HandlerContextKey.SIGNING_REGION);
        ApiCallAttemptMonitoringEvent lastApiCallAttempt = request.getHandlerContext(LAST_CALL_ATTEMPT);

        Long timestamp = null;
        Long latency = null;
        Integer requestCount = 0;
        AWSRequestMetrics metrics = request.getAWSRequestMetrics();

        if (metrics != null) {
            TimingInfo timingInfo = metrics.getTimingInfo();
            requestCount = timingInfo.getCounter(AWSRequestMetrics.Field.RequestCount.name()) == null ? 0 :
                           timingInfo.getCounter(AWSRequestMetrics.Field.RequestCount.name()).intValue();

            TimingInfo latencyTimingInfo = timingInfo.getSubMeasurement(AwsClientSideMonitoringMetrics.ApiCallLatency.name());
            if (latencyTimingInfo != null) {
                latency = convertToLongIfNotNull(latencyTimingInfo.getTimeTakenMillisIfKnown());
                timestamp = latencyTimingInfo.getStartEpochTimeMilliIfKnown();
            }
        }

        ApiCallMonitoringEvent event = new ApiCallMonitoringEvent()
                .withApi(apiName)
                .withVersion(VERSION)
                .withRegion(region)
                .withService(serviceId)
                .withClientId(clientId)
                .withAttemptCount(requestCount)
                .withLatency(latency)
                .withUserAgent(trimValueIfExceedsMaxLength(USER_AGENT_KEY, getDefaultUserAgent(request)))
                .withTimestamp(timestamp);

        if (lastApiCallAttempt != null) {
            event.withFinalAwsException(lastApiCallAttempt.getAwsException())
                 .withFinalAwsExceptionMessage(lastApiCallAttempt.getAwsExceptionMessage())
                 .withFinalSdkException(lastApiCallAttempt.getSdkException())
                 .withFinalSdkExceptionMessage(lastApiCallAttempt.getSdkExceptionMessage())
                 .withFinalHttpStatusCode(lastApiCallAttempt.getHttpStatusCode());
        }

        return event;
    }
820729
protected Pair<Set<Event>, Collection<MultifactorAuthenticationProvider>> filterEventsByMultifactorAuthenticationProvider(
        final Set<Event> resolveEvents, final Authentication authentication,
        final RegisteredService registeredService, final HttpServletRequest request) {
        LOGGER.debug("Locating multifactor providers to determine support for this authentication sequence");
        val providers = MultifactorAuthenticationUtils.getAvailableMultifactorAuthenticationProviders(
            getWebflowEventResolutionConfigurationContext().getApplicationContext());

        if (providers.isEmpty()) {
            LOGGER.debug("No providers are available to honor this request. Moving on...");
            return Pair.of(resolveEvents, new HashSet<>(0));
        }

        val providerValues = providers.values();

        providerValues.removeIf(p -> resolveEvents.stream().noneMatch(e -> p.matches(e.getId())));
        resolveEvents.removeIf(e -> providerValues.stream().noneMatch(p -> p.matches(e.getId())));

        LOGGER.debug("Finalized set of resolved events are [{}]", resolveEvents);
        return Pair.of(resolveEvents, providerValues);
    }
389473
protected void enforceTicketValidationAuthorizationFor(final HttpServletRequest request, final Service service, final Assertion assertion) {
        val authorizers = serviceValidateConfigurationContext.getValidationAuthorizers().getAuthorizers();
        for (val a : authorizers) {
            try {
                a.authorize(request, service, assertion);
            } catch (final Exception e) {
                throw new UnauthorizedServiceTicketValidationException(service);
            }
        }
    }
845741
private int sequentialFailureCount(List<AuditEvent> events) {
        int failureCount = 0;
        for (AuditEvent event : events) {
            if (event.getType() == failureEventType) {
                failureCount++;
            } else if (event.getType() == successEventType) {
                // Successful authentication occurred within last allowable
                // failures, so ignore
                break;
            }
        }
        return failureCount;
    }