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

The following examples show how to use org.jasig.cas.web.support.WebUtils#getHttpServletRequest() . 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: TerminateWebSessionListener.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public void sessionEnded(final RequestContext context, final FlowSession session, final String outcome,
                         final AttributeMap output) {

    if ( session.isRoot() ) {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        // get session but don't create it if it doesn't already exist
        final HttpSession webSession = request.getSession(false);

        if (webSession != null) {
            LOGGER.debug("Terminate web session {} in {} seconds", webSession.getId(), this.timeToDieInSeconds);
            // set the web session to die in timeToDieInSeconds
            webSession.setMaxInactiveInterval(this.timeToDieInSeconds);
        }
    }
}
 
Example 2
Source File: PrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final String remoteUser = request.getRemoteUser();

    if (StringUtils.hasText(remoteUser)) {
        logger.debug("Remote  User [{}] found in HttpServletRequest", remoteUser);
        return new PrincipalBearingCredential(new SimplePrincipal(remoteUser));
    }

    logger.debug("Remote User not found in HttpServletRequest.");

    return null;
}
 
Example 3
Source File: SpnegoCredentialsAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);

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

    if (StringUtils.hasText(authorizationHeader)
            && authorizationHeader.startsWith(this.messageBeginPrefix)
            && authorizationHeader.length() > this.messageBeginPrefix.length()) {

        logger.debug("SPNEGO Authorization header found with {} bytes",
                authorizationHeader.length() - this.messageBeginPrefix.length());

        final byte[] token = CompressionUtils.decodeBase64ToByteArray(authorizationHeader.substring(this.messageBeginPrefix.length()));
        if (token == null) {
            logger.warn("Could not compress authorization header in base64");
            return null;
        }
        logger.debug("Obtained token: {}", new String(token, Charset.defaultCharset()));
        return new SpnegoCredential(token);
    }

    return null;
}
 
Example 4
Source File: BaseSpnegoKnownClientSystemsFilterAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Pulls the remote IP from the current HttpServletRequest, or grabs the value
 * for the specified alternative attribute (say, for proxied requests).  Falls
 * back to providing the "normal" remote address if no value can be retrieved
 * from the specified alternative header value.
 * @param context the context
 * @return the remote ip
 */
private String getRemoteIp(@NotNull final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    String userAddress = request.getRemoteAddr();
    logger.debug("Remote Address = {}", userAddress);

    if (StringUtils.isNotBlank(this.alternativeRemoteHostAttribute)) {

        userAddress = request.getHeader(this.alternativeRemoteHostAttribute);
        logger.debug("Header Attribute [{}] = [{}]", this.alternativeRemoteHostAttribute, userAddress);

        if (StringUtils.isBlank(userAddress)) {
            userAddress = request.getRemoteAddr();
            logger.warn("No value could be retrieved from the header [{}]. Falling back to [{}].",
                    this.alternativeRemoteHostAttribute, userAddress);
        }
    }
    return userAddress;
}
 
Example 5
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 6
Source File: PrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final String remoteUser = request.getRemoteUser();

    if (StringUtils.hasText(remoteUser)) {
        logger.debug("Remote  User [{}] found in HttpServletRequest", remoteUser);
        return new PrincipalBearingCredential(this.principalFactory.createPrincipal(remoteUser));
    }

    logger.debug("Remote User not found in HttpServletRequest.");

    return null;
}
 
Example 7
Source File: PrincipalFromRequestUserPrincipalNonInteractiveCredentialsAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(
        final RequestContext context) {
    final HttpServletRequest request = WebUtils
            .getHttpServletRequest(context);
    final Principal principal = request.getUserPrincipal();

    if (principal != null) {

        logger.debug("UserPrincipal [{}] found in HttpServletRequest", principal.getName());
        return new PrincipalBearingCredential(this.principalFactory.createPrincipal(principal.getName()));
    }

    logger.debug("UserPrincipal not found in HttpServletRequest.");
    return null;
}
 
Example 8
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 9
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 10
Source File: InitialFlowSetupAction.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    if (!this.pathPopulated) {
        final String contextPath = context.getExternalContext().getContextPath();
        final String cookiePath = StringUtils.hasText(contextPath) ? contextPath + '/' : "/";
        logger.info("Setting path for cookies to: {} ", cookiePath);
        this.warnCookieGenerator.setCookiePath(cookiePath);
        this.ticketGrantingTicketCookieGenerator.setCookiePath(cookiePath);
        this.pathPopulated = true;
    }

    WebUtils.putTicketGrantingTicketInScopes(context,
            this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));

    WebUtils.putWarningCookie(context,
            Boolean.valueOf(this.warnCookieGenerator.retrieveCookieValue(request)));

    final Service service = WebUtils.getService(this.argumentExtractors, context);


    if (service != null) {
        logger.debug("Placing service in context scope: [{}]", service.getId());

        final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
        if (registeredService != null && registeredService.getAccessStrategy().isServiceAccessAllowed()) {
            logger.debug("Placing registered service [{}] with id [{}] in context scope",
                    registeredService.getServiceId(),
                    registeredService.getId());
            WebUtils.putRegisteredService(context, registeredService);
        }
    } else if (!this.enableFlowOnAbsentServiceRequest) {
        logger.warn("No service authentication request is available at [{}]. CAS is configured to disable the flow.",
                WebUtils.getHttpServletRequest(context).getRequestURL());
        throw new NoSuchFlowExecutionException(context.getFlowExecutionContext().getKey(),
                new UnauthorizedServiceException("screen.service.required.message", "Service is required"));
    }
    WebUtils.putService(context, service);
    return result("success");
}
 
Example 11
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 12
Source File: InitialFlowSetupAction.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) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);

    final String contextPath = context.getExternalContext().getContextPath();
    final String cookiePath = StringUtils.hasText(contextPath) ? contextPath + '/' : "/";

    if (!StringUtils.hasText(warnCookieGenerator.getCookiePath())) {
        logger.info("Setting path for cookies for warn cookie generator to: " + cookiePath);
        this.warnCookieGenerator.setCookiePath(cookiePath);
    } else {
        logger.debug("Warning cookie domain is set to " + warnCookieGenerator.getCookieDomain()
                + " and path " +  warnCookieGenerator.getCookiePath());
    }
    if (!StringUtils.hasText(ticketGrantingTicketCookieGenerator.getCookiePath())) {
        logger.info("Setting path for cookies for TGC cookie generator to: " + cookiePath);
        this.ticketGrantingTicketCookieGenerator.setCookiePath(cookiePath);
    } else {
        logger.debug("TGC cookie domain is set to " + ticketGrantingTicketCookieGenerator.getCookieDomain()
                + " and path " +  ticketGrantingTicketCookieGenerator.getCookiePath());
    }

    context.getFlowScope().put(
        "ticketGrantingTicketId", this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));
    context.getFlowScope().put(
        "warnCookieValue",
        Boolean.valueOf(this.warnCookieGenerator.retrieveCookieValue(request)));

    final Service service = WebUtils.getService(this.argumentExtractors,
        context);

    if (service != null && logger.isDebugEnabled()) {
        logger.debug("Placing service in FlowScope: " + service.getId());
    }

    context.getFlowScope().put("service", service);

    return result("success");
}
 
Example 13
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 14
Source File: AuthenticationViaFormAction.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
public final void doBind(final RequestContext context, final Credential credential) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);

    if (this.credentialsBinder != null && this.credentialsBinder.supports(credential.getClass())) {
        this.credentialsBinder.bind(request, credential);
    }
}
 
Example 15
Source File: RemoteAddressNonInteractiveCredentialsAction.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final String remoteAddress = request.getRemoteAddr();

    if (StringUtils.hasText(remoteAddress)) {
        return new RemoteAddressCredential(remoteAddress);
    }

    logger.debug("No remote address found.");
    return null;
}
 
Example 16
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 17
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 18
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();
}
 
Example 19
Source File: SamlMetadataUIParserAction.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
@Override
protected Event doExecute(final RequestContext requestContext) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(requestContext);
    final String entityId = request.getParameter(this.entityIdParameterName);
    if (StringUtils.isBlank(entityId)) {
        logger.debug("No entity id found for parameter [{}]", this.entityIdParameterName);
        return success();
    }

    final WebApplicationService service = new SimpleWebApplicationServiceImpl(entityId);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        logger.debug("Entity id [{}] is not recognized/allowed by the CAS service registry", entityId);
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE,
                "Entity " + entityId + " not recognized");
    }

    final EntityDescriptor entityDescriptor = this.metadataAdapter.getEntityDescriptorForEntityId(entityId);
    if (entityDescriptor == null) {
        logger.debug("Entity descriptor not found for [{}]", entityId);
        return success();
    }

    final SPSSODescriptor spssoDescriptor = getSPSSODescriptor(entityDescriptor);
    if (spssoDescriptor == null) {
        logger.debug("SP SSO descriptor not found for [{}]", entityId);
        return success();
    }

    final Extensions extensions = spssoDescriptor.getExtensions();
    final List<XMLObject> spExtensions = extensions.getUnknownXMLObjects(UIInfo.DEFAULT_ELEMENT_NAME);
    if (spExtensions.isEmpty()) {
        logger.debug("No extensions are found for [{}]", UIInfo.DEFAULT_ELEMENT_NAME.getNamespaceURI());
        return success();
    }

    final SimpleMetadataUIInfo mdui = new SimpleMetadataUIInfo(registeredService);

    for (final XMLObject obj : spExtensions) {
        if (obj instanceof UIInfo) {
            final UIInfo uiInfo = (UIInfo) obj;
            logger.debug("Found UI info for [{}] and added to flow context", entityId);
            mdui.setUIInfo(uiInfo);
        }
    }

    requestContext.getFlowScope().put(MDUI_FLOW_PARAMETER_NAME, mdui);
    return success();
}
 
Example 20
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();
}