Java Code Examples for org.jasig.cas.web.support.WebUtils#getHttpServletResponse()

The following examples show how to use org.jasig.cas.web.support.WebUtils#getHttpServletResponse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Prepare the data for the login page.
 *
 * @param context The current webflow context
 */
protected void prepareForLoginPage(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // save parameters in web session
    final WebApplicationService service = WebUtils.getService(context);
    logger.debug("save service: {}", service);
    session.setAttribute(SERVICE, service);
    saveRequestParameter(request, session, THEME);
    saveRequestParameter(request, session, LOCALE);
    saveRequestParameter(request, session, METHOD);

    // for all clients, generate redirection urls
    for (final Client client : this.clients.findAllClients()) {
        final String key = client.getName() + "Url";
        final BaseClient baseClient = (BaseClient) client;
        final String redirectionUrl = baseClient.getRedirectionUrl(webContext);
        logger.debug("{} -> {}", key, redirectionUrl);
        context.getFlowScope().put(key, redirectionUrl);
    }
}
 
Example 2
Source File: TerminateSessionAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Terminates the CAS SSO session by destroying the TGT (if any) and removing cookies related to the SSO session.
 *
 * @param context Request context.
 *
 * @return "success"
 */
public Event terminate(final RequestContext context) {
    // in login's webflow : we can get the value from context as it has already been stored
    String tgtId = WebUtils.getTicketGrantingTicketId(context);
    // for logout, we need to get the cookie's value
    if (tgtId == null) {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        tgtId = this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request);
    }
    if (tgtId != null) {
        WebUtils.putLogoutRequests(context, this.centralAuthenticationService.destroyTicketGrantingTicket(tgtId));
    }
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    this.ticketGrantingTicketCookieGenerator.removeCookie(response);
    this.warnCookieGenerator.removeCookie(response);
    return this.eventFactorySupport.success(this);
}
 
Example 3
Source File: SpnegoCredentialsAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Sets the response header based on the retrieved tocken.
 *
 * @param context the context
 * @param credential the credential
 */
private void setResponseHeader(final RequestContext context,
        final Credential credential) {
    if (credential == null) {
        return;
    }

    final HttpServletResponse response = WebUtils
            .getHttpServletResponse(context);
    final SpnegoCredential spnegoCredentials = (SpnegoCredential) credential;
    final byte[] nextToken = spnegoCredentials.getNextToken();
    if (nextToken != null) {
        logger.debug("Obtained output token: {}", new String(nextToken, Charset.defaultCharset()));
        response.setHeader(SpnegoConstants.HEADER_AUTHENTICATE, (this.ntlm
                ? SpnegoConstants.NTLM : SpnegoConstants.NEGOTIATE)
                + ' ' + CompressionUtils.encodeBase64(nextToken));
    } else {
        logger.debug("Unable to obtain the output token required.");
    }

    if (spnegoCredentials.getPrincipal() == null && send401OnAuthenticationFailure) {
        logger.debug("Setting HTTP Status to 401");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example 4
Source File: ClientAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Prepare the data for the login page.
 *
 * @param context The current webflow context
 */
protected void prepareForLoginPage(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // save parameters in web session
    final Service service = (Service) context.getFlowScope().get(SERVICE);
    logger.info("save service: {}", service);
    session.setAttribute(SERVICE, service);
    saveRequestParameter(request, session, THEME);
    saveRequestParameter(request, session, LOCALE);
    saveRequestParameter(request, session, METHOD);

    // for all clients, generate redirection urls
    for (final Client client : this.clients.findAllClients()) {
        final String key = client.getName() + "Url";
        final BaseClient baseClient = (BaseClient) client;
        final String redirectionUrl = baseClient.getRedirectionUrl(webContext);
        logger.info("{} -> {}", key, redirectionUrl);
        context.getFlowScope().put(key, redirectionUrl);
    }
}
 
Example 5
Source File: TerminateSessionAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Terminates the CAS SSO session by destroying the TGT (if any) and removing cookies related to the SSO session.
 *
 * @param context Request context.
 *
 * @return "success"
 */
public Event terminate(final RequestContext context) {
    // in login's webflow : we can get the value from context as it has already been stored
    String tgtId = WebUtils.getTicketGrantingTicketId(context);
    // for logout, we need to get the cookie's value
    if (tgtId == null) {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        tgtId = this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request);
    }
    if (tgtId != null) {
        WebUtils.putLogoutRequests(context, this.centralAuthenticationService.destroyTicketGrantingTicket(tgtId));
    }
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    this.ticketGrantingTicketCookieGenerator.removeCookie(response);
    this.warnCookieGenerator.removeCookie(response);
    return this.eventFactorySupport.success(this);
}
 
Example 6
Source File: SpnegoCredentialsAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
private void setResponseHeader(final RequestContext context,
        final Credential credential) {
    if (credential == null) {
        return;
    }

    final HttpServletResponse response = WebUtils
            .getHttpServletResponse(context);
    final SpnegoCredential spnegoCredentials = (SpnegoCredential) credential;
    final byte[] nextToken = spnegoCredentials.getNextToken();
    if (nextToken != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Obtained output token: " + new String(nextToken));
        }
        response.setHeader(SpnegoConstants.HEADER_AUTHENTICATE, (this.ntlm
                ? SpnegoConstants.NTLM : SpnegoConstants.NEGOTIATE)
                + " " + Base64.encode(nextToken));
    } else {
        logger.debug("Unable to obtain the output token required.");
    }

    if (spnegoCredentials.getPrincipal() == null && send401OnAuthenticationFailure) {
        logger.debug("Setting HTTP Status to 401");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
 
Example 7
Source File: AuthenticationViaFormAction.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Put warn cookie if request parameter present.
 *
 * @param context the context
 */
private void putWarnCookieIfRequestParameterPresent(final RequestContext context) {
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);

    if (StringUtils.isNotBlank(context.getExternalContext().getRequestParameterMap().get("warn"))) {
        this.warnCookieGenerator.addCookie(response, "true");
    } else {
        this.warnCookieGenerator.removeCookie(response);
    }
}
 
Example 8
Source File: AbstractLogoutAction.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
protected final Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);

    preventCaching(response);

    return doInternalExecute(request, response, context);
}
 
Example 9
Source File: AuthenticationViaFormAction.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
private void putWarnCookieIfRequestParameterPresent(final RequestContext context) {
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);

    if (StringUtils.hasText(context.getExternalContext().getRequestParameterMap().get("warn"))) {
        this.warnCookieGenerator.addCookie(response, "true");
    } else {
        this.warnCookieGenerator.removeCookie(response);
    }
}
 
Example 10
Source File: AbstractLogoutAction.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
protected final Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);

    preventCaching(response);

    return doInternalExecute(request, response, context);
}
 
Example 11
Source File: SpnegoNegociateCredentialsAction.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
protected Event doExecute(final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils
            .getHttpServletResponse(context);
    final String authorizationHeader = request
            .getHeader(SpnegoConstants.HEADER_AUTHORIZATION);
    final String userAgent = request
            .getHeader(SpnegoConstants.HEADER_USER_AGENT);

    if (StringUtils.hasText(userAgent) && isSupportedBrowser(userAgent)) {
        if (!StringUtils.hasText(authorizationHeader)
                || !authorizationHeader.startsWith(this.messageBeginPrefix)
                || authorizationHeader.length() <= this.messageBeginPrefix
                .length()) {
            if (logger.isDebugEnabled()) {
                logger
                .debug("Authorization header not found. Sending WWW-Authenticate header");
            }
            response.setHeader(SpnegoConstants.HEADER_AUTHENTICATE,
                    this.ntlm ? SpnegoConstants.NTLM
                            : SpnegoConstants.NEGOTIATE);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            // The responseComplete flag tells the pausing view-state not to render the response
            // because another object has taken care of it. If mixed mode authentication is allowed
            // then responseComplete should not be called so that webflow will display the login page.
            if (!this.mixedModeAuthentication) {
                context.getExternalContext().recordResponseComplete();
            }
        }
    }
    return success();
}
 
Example 12
Source File: ClientAction.java    From oxTrust with MIT License 5 votes vote down vote up
/**
 * {@InheritDoc}
 */
@Override
protected Event doExecute(final RequestContext context) throws Exception {
	final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
	final HttpServletResponse response = WebUtils.getHttpServletResponse(context);

	// Web context
	final WebContext webContext = new J2EContext(request, response);

	// It's an authentication
	if (client.isAuthorizationResponse(webContext)) {
		logger.info("Procession authentication request");

		// Check if oxAuth request state is correct
		if (!client.isValidRequestState(webContext)) {
			logger.warn("The state in session and in request are not equals");

			// Reinit login page
			prepareForLoginPage(context, webContext);

			return new Event(this, "stop");
		}

		// Try to authenticate
		final ClientCredential credentials = getClientCrendentials(context, webContext);
		if (credentials != null) {
			WebUtils.putTicketGrantingTicketInRequestScope(context,
					this.centralAuthenticationService.createTicketGrantingTicket(credentials));
			return success();
		}
	}

	// Go to login page
	prepareForLoginPage(context, webContext);

	return error();
}
 
Example 13
Source File: ClientAction.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // get client
    final String clientName = request.getParameter(this.clients.getClientNameParameter());
    logger.debug("clientName: {}", clientName);

    // it's an authentication
    if (StringUtils.isNotBlank(clientName)) {
        // get client
        final BaseClient<Credentials, CommonProfile> client =
                (BaseClient<Credentials, CommonProfile>) this.clients
                .findClient(clientName);
        logger.debug("client: {}", client);

        // Only supported protocols
        final Mechanism mechanism = client.getMechanism();
        if (!SUPPORTED_PROTOCOLS.contains(mechanism)) {
            throw new TechnicalException("Only CAS, OAuth, OpenID and SAML protocols are supported: " + client);
        }

        // get credentials
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            logger.debug("credentials: {}", credentials);
        } catch (final RequiresHttpAction e) {
            logger.debug("requires http action: {}", e);
            response.flushBuffer();
            final ExternalContext externalContext = ExternalContextHolder.getExternalContext();
            externalContext.recordResponseComplete();
            return new Event(this, "stop");
        }

        // retrieve parameters from web session
        final Service service = (Service) session.getAttribute(SERVICE);
        context.getFlowScope().put(SERVICE, service);
        logger.debug("retrieve service: {}", service);
        if (service != null) {
            request.setAttribute(SERVICE, service.getId());
        }
        restoreRequestAttribute(request, session, THEME);
        restoreRequestAttribute(request, session, LOCALE);
        restoreRequestAttribute(request, session, METHOD);

        // credentials not null -> try to authenticate
        if (credentials != null) {
            final TicketGrantingTicket tgt = 
                    this.centralAuthenticationService.createTicketGrantingTicket(new ClientCredential(credentials));
            WebUtils.putTicketGrantingTicketInScopes(context, tgt);
            return success();
        }
    }

    // no or aborted authentication : go to login page
    prepareForLoginPage(context);
    return error();
}
 
Example 14
Source File: SpnegoNegociateCredentialsAction.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
@Override
protected Event doExecute(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);

    final String authorizationHeader = request.getHeader(SpnegoConstants.HEADER_AUTHORIZATION);
    final String userAgent = request.getHeader(SpnegoConstants.HEADER_USER_AGENT);

    LOGGER.debug("Authorization header [{}], User Agent header [{}]", authorizationHeader, userAgent);

    if (!StringUtils.hasText(userAgent) || this.supportedBrowser.isEmpty()) {
        LOGGER.debug("User Agent header [{}] is empty, or no browsers are supported", userAgent);
        return success();
    }

    if (!isSupportedBrowser(userAgent)) {
        LOGGER.debug("User Agent header [{}] is not supported in the list of supported browsers [{}]",
                userAgent, this.supportedBrowser);
        return success();
    }

    if (!StringUtils.hasText(authorizationHeader)
            || !authorizationHeader.startsWith(this.messageBeginPrefix)
            || authorizationHeader.length() <= this.messageBeginPrefix
            .length()) {

        final String wwwHeader = this.ntlm ? SpnegoConstants.NTLM : SpnegoConstants.NEGOTIATE;
        LOGGER.debug("Authorization header not found or does not match the message prefix [{}]. Sending [{}] header [{}]",
                this.messageBeginPrefix, SpnegoConstants.HEADER_AUTHENTICATE, wwwHeader);
        response.setHeader(SpnegoConstants.HEADER_AUTHENTICATE, wwwHeader);

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // The responseComplete flag tells the pausing view-state not to render the response
        // because another object has taken care of it. If mixed mode authentication is allowed
        // then responseComplete should not be called so that webflow will display the login page.
        if (!this.mixedModeAuthentication) {
            LOGGER.debug("Mixed-mode authentication is disabled. Executing completion of response");
            context.getExternalContext().recordResponseComplete();
        }
    }
    return success();
}
 
Example 15
Source File: ClientAction.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // get client
    //final String clientName = request.getParameter(this.clients.getClientNameParameter());
    final String clientName = request.getParameter("state");
    //logger.debug("clientName : {}", clientName);
    logger.info("clientName : {}", clientName);

    // it's an authentication
    if (StringUtils.isNotBlank(clientName)) {
        // get client
        final BaseClient<Credentials, CommonProfile> client =
                (BaseClient<Credentials, CommonProfile>) this.clients
                .findClient(clientName);
        logger.info("client : {}", client);

        // Only supported protocols
        final Mechanism mechanism = client.getMechanism();
        logger.info("mechanism == " + mechanism.name());
        if (!SUPPORTED_PROTOCOLS.contains(mechanism)) {
            throw new TechnicalException("Only CAS, OAuth, OpenID and SAML protocols are supported: " + client);
        }

        // get credentials
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            logger.info("credentials : {}", credentials);
        } catch (final RequiresHttpAction e) {
            logger.info("requires http action : {}", e);
            response.flushBuffer();
            ExternalContext externalContext = ExternalContextHolder.getExternalContext();
            externalContext.recordResponseComplete();
            return new Event(this, "stop");
        }

        // retrieve parameters from web session
        final Service service = (Service) session.getAttribute(SERVICE);
        context.getFlowScope().put(SERVICE, service);
        logger.info("retrieve service: {}", service);
        if (service != null) {
            request.setAttribute(SERVICE, service.getId());
        }
        restoreRequestAttribute(request, session, THEME);
        restoreRequestAttribute(request, session, LOCALE);
        restoreRequestAttribute(request, session, METHOD);

        // credentials not null -> try to authenticate
        if (credentials != null) {
            logger.info("credentials is not null : {}", credentials);
            WebUtils.putTicketGrantingTicketInRequestScope(context,
                    this.centralAuthenticationService.createTicketGrantingTicket(new ClientCredential(credentials)));
            return success();
        }
    }

    // no or aborted authentication : go to login page
    prepareForLoginPage(context);
    return error();
}