Search in sources :

Example 96 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project cas by apereo.

the class ServiceWarningAction method doExecute.

@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final Service service = WebUtils.getService(context);
    final String ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context);
    final Authentication authentication = this.ticketRegistrySupport.getAuthenticationFrom(ticketGrantingTicket);
    if (authentication == null) {
        throw new InvalidTicketException(new AuthenticationException("No authentication found for ticket " + ticketGrantingTicket), ticketGrantingTicket);
    }
    final Credential credential = WebUtils.getCredential(context);
    final AuthenticationResultBuilder authenticationResultBuilder = authenticationSystemSupport.establishAuthenticationContextFromInitial(authentication, credential);
    final AuthenticationResult authenticationResult = authenticationResultBuilder.build(service);
    final ServiceTicket serviceTicketId = this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicket, service, authenticationResult);
    WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);
    if (request.getParameterMap().containsKey("ignorewarn")) {
        if (Boolean.valueOf(request.getParameter("ignorewarn").toString())) {
            this.warnCookieGenerator.removeCookie(response);
        }
    }
    return new Event(this, CasWebflowConstants.STATE_ID_REDIRECT);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Credential(org.apereo.cas.authentication.Credential) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) Authentication(org.apereo.cas.authentication.Authentication) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) HttpServletResponse(javax.servlet.http.HttpServletResponse) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) Service(org.apereo.cas.authentication.principal.Service) Event(org.springframework.webflow.execution.Event) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult)

Example 97 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project cas by apereo.

the class BasicAuthenticationAction method constructCredentialsFromRequest.

@Override
protected Credential constructCredentialsFromRequest(final RequestContext requestContext) {
    try {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(requestContext);
        final HttpServletResponse response = WebUtils.getHttpServletResponse(requestContext);
        final BasicAuthExtractor extractor = new BasicAuthExtractor(this.getClass().getSimpleName());
        final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response);
        final UsernamePasswordCredentials credentials = extractor.extract(webContext);
        if (credentials != null) {
            LOGGER.debug("Received basic authentication request from credentials [{}]", credentials);
            return new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword());
        }
    } catch (final Exception e) {
        LOGGER.warn(e.getMessage(), e);
    }
    return null;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) WebContext(org.pac4j.core.context.WebContext) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 98 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project cas by apereo.

the class ValidateCaptchaAction method doExecute.

@Override
protected Event doExecute(final RequestContext requestContext) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(requestContext);
    final String gRecaptchaResponse = request.getParameter("g-recaptcha-response");
    if (StringUtils.isBlank(gRecaptchaResponse)) {
        LOGGER.warn("Recaptcha response is missing from the request");
        return getError(requestContext);
    }
    try {
        final URL obj = new URL(recaptchaProperties.getVerifyUrl());
        final HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", WebUtils.getHttpServletRequestUserAgent());
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        final String postParams = "secret=" + recaptchaProperties.getSecret() + "&response=" + gRecaptchaResponse;
        LOGGER.debug("Sending 'POST' request to URL: [{}]", obj);
        con.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.writeBytes(postParams);
            wr.flush();
        }
        final int responseCode = con.getResponseCode();
        LOGGER.debug("Response Code: [{}]", responseCode);
        if (responseCode == HttpStatus.OK.value()) {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
                final String response = in.lines().collect(Collectors.joining());
                LOGGER.debug("Google captcha response received: [{}]", response);
                final JsonNode node = READER.readTree(response);
                if (node.has("success") && node.get("success").booleanValue()) {
                    return null;
                }
            }
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return getError(requestContext);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) InputStreamReader(java.io.InputStreamReader) DataOutputStream(java.io.DataOutputStream) BufferedReader(java.io.BufferedReader) JsonNode(com.fasterxml.jackson.databind.JsonNode) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 99 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project cas by apereo.

the class FrontChannelLogoutAction method doInternalExecute.

@Override
protected Event doInternalExecute(final HttpServletRequest request, final HttpServletResponse response, final RequestContext context) throws Exception {
    final List<LogoutRequest> logoutRequests = WebUtils.getLogoutRequests(context);
    final Map<LogoutRequest, LogoutHttpMessage> logoutUrls = new HashMap<>();
    if (logoutRequests != null) {
        logoutRequests.stream().filter(r -> r.getStatus() == LogoutRequestStatus.NOT_ATTEMPTED).forEach(r -> {
            LOGGER.debug("Using logout url [{}] for front-channel logout requests", r.getLogoutUrl().toExternalForm());
            final String logoutMessage = this.logoutManager.createFrontChannelLogoutMessage(r);
            LOGGER.debug("Front-channel logout message to send is [{}]", logoutMessage);
            final LogoutHttpMessage msg = new LogoutHttpMessage(r.getLogoutUrl(), logoutMessage, true);
            logoutUrls.put(r, msg);
            r.setStatus(LogoutRequestStatus.SUCCESS);
            r.getService().setLoggedOutAlready(true);
        });
        if (!logoutUrls.isEmpty()) {
            context.getFlowScope().put("logoutUrls", logoutUrls);
            return new EventFactorySupport().event(this, "propagate");
        }
    }
    return new EventFactorySupport().event(this, FINISH_EVENT);
}
Also used : LogoutManager(org.apereo.cas.logout.LogoutManager) LogoutRequest(org.apereo.cas.logout.LogoutRequest) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) HttpServletResponse(javax.servlet.http.HttpServletResponse) LogoutRequestStatus(org.apereo.cas.logout.LogoutRequestStatus) HashMap(java.util.HashMap) EventFactorySupport(org.springframework.webflow.action.EventFactorySupport) RequestContext(org.springframework.webflow.execution.RequestContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) List(java.util.List) Map(java.util.Map) LogoutHttpMessage(org.apereo.cas.logout.LogoutHttpMessage) WebUtils(org.apereo.cas.web.support.WebUtils) Event(org.springframework.webflow.execution.Event) HashMap(java.util.HashMap) LogoutHttpMessage(org.apereo.cas.logout.LogoutHttpMessage) LogoutRequest(org.apereo.cas.logout.LogoutRequest) EventFactorySupport(org.springframework.webflow.action.EventFactorySupport)

Example 100 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project cas by apereo.

the class DateTimeAuthenticationRequestRiskCalculator method calculateScore.

@Override
protected BigDecimal calculateScore(final HttpServletRequest request, final Authentication authentication, final RegisteredService service, final Collection<CasEvent> events) {
    final ZonedDateTime timestamp = ZonedDateTime.now();
    LOGGER.debug("Filtering authentication events for timestamp [{}]", timestamp);
    final long count = events.stream().filter(e -> e.getCreationTime().getHour() == timestamp.getHour() || e.getCreationTime().plusHours(windowInHours).getHour() == timestamp.getHour() || e.getCreationTime().minusHours(windowInHours).getHour() == timestamp.getHour()).count();
    LOGGER.debug("Total authentication events found for [{}]: [{}]", timestamp, count);
    if (count == events.size()) {
        LOGGER.debug("Principal [{}] has always authenticated from [{}]", authentication.getPrincipal(), timestamp);
        return LOWEST_RISK_SCORE;
    }
    return getFinalAveragedScore(count, events.size());
}
Also used : CasEventRepository(org.apereo.cas.support.events.CasEventRepository) BigDecimal(java.math.BigDecimal) HttpServletRequest(javax.servlet.http.HttpServletRequest) Logger(org.slf4j.Logger) Authentication(org.apereo.cas.authentication.Authentication) ZonedDateTime(java.time.ZonedDateTime) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) RegisteredService(org.apereo.cas.services.RegisteredService) CasEvent(org.apereo.cas.support.events.dao.CasEvent) ZonedDateTime(java.time.ZonedDateTime)

Aggregations

HttpServletRequest (javax.servlet.http.HttpServletRequest)2488 HttpServletResponse (javax.servlet.http.HttpServletResponse)1308 Test (org.junit.Test)987 IOException (java.io.IOException)595 ServletException (javax.servlet.ServletException)498 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)223 FilterChain (javax.servlet.FilterChain)200 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)196 Test (org.testng.annotations.Test)168 Request (org.eclipse.jetty.server.Request)164 CountDownLatch (java.util.concurrent.CountDownLatch)160 HttpServlet (javax.servlet.http.HttpServlet)156 HttpSession (javax.servlet.http.HttpSession)150 HashMap (java.util.HashMap)130 PrintWriter (java.io.PrintWriter)121 Map (java.util.Map)100 InterruptedIOException (java.io.InterruptedIOException)97 ServletRequest (javax.servlet.ServletRequest)95 ServletContext (javax.servlet.ServletContext)91 ServletOutputStream (javax.servlet.ServletOutputStream)90