Java Code Examples for org.springframework.webflow.execution.RequestContext

The following examples show how to use org.springframework.webflow.execution.RequestContext. These examples are extracted from open source projects. 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 Project: cxf-fediz   Source File: TrustedIdpProtocolAction.java    License: Apache License 2.0 6 votes vote down vote up
public SecurityToken mapSignInResponse(RequestContext requestContext, String trustedIdpRealm) {
    LOG.info("Prepare validate SignInResponse of Trusted IDP '{}'", trustedIdpRealm);

    Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(requestContext, IDP_CONFIG);

    TrustedIdp trustedIdp = idpConfig.findTrustedIdp(trustedIdpRealm);
    if (trustedIdp == null) {
        LOG.error("TrustedIdp '{}' not configured", trustedIdpRealm);
        throw new IllegalStateException("TrustedIdp '" + trustedIdpRealm + "'");
    }

    String protocol = trustedIdp.getProtocol();
    LOG.debug("TrustedIdp '{}' supports protocol {}", trustedIdpRealm, protocol);

    TrustedIdpProtocolHandler protocolHandler = trustedIdpProtocolHandlers.getProtocolHandler(protocol);
    if (protocolHandler == null) {
        LOG.error("No ProtocolHandler found for {}", protocol);
        throw new IllegalStateException("No ProtocolHandler found for '" + protocol + "'");
    }
    SecurityToken token = protocolHandler.mapSignInResponse(requestContext, idpConfig, trustedIdp);
    if (token != null) {
        LOG.info("SignInResponse successfully validated and SecurityToken created");
    }
    return token;
}
 
Example 2
@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final String userName = this.extractor
            .extractLocalUsernameFromUri(context.getRequestParameters()
                    .get("openid.identity"));
    final Service service = WebUtils.getService(context);

    context.getExternalContext().getSessionMap().put("openIdLocalId", userName);

    // clear the service because otherwise we can fake the username
    if (service instanceof OpenIdService && userName == null) {
        context.getFlowScope().remove("service");
    }

    if (ticketGrantingTicketId == null || userName == null) {
        return null;
    }

    return new OpenIdCredential(
            ticketGrantingTicketId, userName);
}
 
Example 3
@Before
public void onSetUp() throws Exception {
    final LogoutManager logoutManager = new LogoutManagerImpl(mock(ServicesManager.class),
            new SimpleHttpClient(), new SamlCompliantLogoutMessageCreator());
    this.frontChannelLogoutAction = new FrontChannelLogoutAction(logoutManager);

    this.request = new MockHttpServletRequest();
    this.response = new MockHttpServletResponse();
    this.requestContext = mock(RequestContext.class);
    final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(this.requestContext.getExternalContext()).thenReturn(servletExternalContext);
    when(servletExternalContext.getNativeRequest()).thenReturn(request);
    when(servletExternalContext.getNativeResponse()).thenReturn(response);
    final LocalAttributeMap flowScope = new LocalAttributeMap();
    when(this.requestContext.getFlowScope()).thenReturn(flowScope);
    final MockFlowExecutionKey mockFlowExecutionKey = new MockFlowExecutionKey(FLOW_EXECUTION_KEY);
    final MockFlowExecutionContext mockFlowExecutionContext = new MockFlowExecutionContext();
    mockFlowExecutionContext.setKey(mockFlowExecutionKey);
    when(this.requestContext.getFlowExecutionContext()).thenReturn(mockFlowExecutionContext);
}
 
Example 4
Source Project: oxTrust   Source File: ClientAction.java    License: MIT License 6 votes vote down vote up
/**
 * Prepare the data for the login page
 * 
 * @param context The current webflow context
 * @param webContext The current web context
 */
protected void prepareForLoginPage(final RequestContext context, final WebContext webContext) {
	// Save parameters in web session
	final Service service = (Service) context.getFlowScope().get(SERVICE);
	if (service != null) {
		webContext.setSessionAttribute(SERVICE, service);
	}
	saveRequestParameter(webContext, THEME);
	saveRequestParameter(webContext, LOCALE);
	saveRequestParameter(webContext, METHOD);

	final String keyRedirectionUrl = this.client.getName() + "Url";
	final String redirectionUrl = this.client.getRedirectionUrl(webContext);
	logger.debug("Generated redirection Url", redirectionUrl);

	context.getFlowScope().put(keyRedirectionUrl, redirectionUrl);

	final String keyAuthMethod = this.client.getName() + "OpenIdDefaultAuthenticator";
	final Boolean keyAuthMethodValue = this.client.isOpenIdDefaultAuthenticator();
	logger.debug("OpenIdDefaultAuthenticator", keyAuthMethodValue);

	context.getFlowScope().put(keyAuthMethod, keyAuthMethodValue);
}
 
Example 5
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 6
Source Project: cxf-fediz   Source File: AuthnRequestParser.java    License: Apache License 2.0 6 votes vote down vote up
public String retrieveRequestId(RequestContext context) {
    SAMLAbstractRequest request =
        (SAMLAbstractRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
    if (request == null) {
        request = (SAMLAbstractRequest)WebUtils.getAttributeFromFlowScope(context,
                                                                          IdpConstants.SAML_LOGOUT_REQUEST);
    }

    if (request != null && request.getRequestId() != null) {
        String id = request.getRequestId();
        LOG.debug("Parsed SAML Request Id: {}", id);
        return id;
    }

    LOG.debug("No AuthnRequest/LogoutRequest available to be parsed");
    return null;
}
 
Example 7
Source Project: cxf-fediz   Source File: TrustedIdpProtocolAction.java    License: Apache License 2.0 6 votes vote down vote up
public String mapSignInRequest(RequestContext requestContext, String trustedIdpRealm) {
    LOG.info("Prepare redirect to Trusted IDP '{}'", trustedIdpRealm);

    Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(requestContext, IDP_CONFIG);

    TrustedIdp trustedIdp = idpConfig.findTrustedIdp(trustedIdpRealm);
    if (trustedIdp == null) {
        LOG.error("TrustedIdp '{}' not configured", trustedIdpRealm);
        throw new IllegalStateException("TrustedIdp '" + trustedIdpRealm + "'");
    }

    String protocol = trustedIdp.getProtocol();
    LOG.debug("TrustedIdp '{}' supports protocol {}", trustedIdpRealm, protocol);

    TrustedIdpProtocolHandler protocolHandler = trustedIdpProtocolHandlers.getProtocolHandler(protocol);
    if (protocolHandler == null) {
        LOG.error("No ProtocolHandler found for {}", protocol);
        throw new IllegalStateException("No ProtocolHandler found for '" + protocol + "'");
    }
    URL redirectUrl = protocolHandler.mapSignInRequest(requestContext, idpConfig, trustedIdp);
    LOG.info("Redirect url {}", redirectUrl.toString());
    return redirectUrl.toString();
}
 
Example 8
@Override
protected Event doExecute(final RequestContext context) {
    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final String ticketGrantingTicketValueFromCookie = (String) context.getFlowScope().get("ticketGrantingTicketId");

    if (ticketGrantingTicketId == null) {
        return success();
    }

    this.ticketGrantingTicketCookieGenerator.addCookie(WebUtils.getHttpServletRequest(context), WebUtils
        .getHttpServletResponse(context), ticketGrantingTicketId);

    if (ticketGrantingTicketValueFromCookie != null && !ticketGrantingTicketId.equals(ticketGrantingTicketValueFromCookie)) {
        this.centralAuthenticationService
            .destroyTicketGrantingTicket(ticketGrantingTicketValueFromCookie);
    }

    return success();
}
 
Example 9
@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
    final X509Certificate[] certificates = (X509Certificate[]) context
            .getExternalContext().getRequestMap().get(
                    CERTIFICATE_REQUEST_ATTRIBUTE);

    if (certificates == null || certificates.length == 0) {
        if (logger.isDebugEnabled()) {
            logger.debug("Certificates not found in request.");
        }
        return null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Certificate found in request.");
    }
    return new X509CertificateCredential(certificates);
}
 
Example 10
Source Project: cxf-fediz   Source File: IdpTokenExpiredAction.java    License: Apache License 2.0 6 votes vote down vote up
public boolean isTokenExpired(String homeRealm, RequestContext context)
    throws Exception {

    SecurityToken idpToken =
        (SecurityToken) WebUtils.getAttributeFromExternalContext(context, homeRealm);
    if (idpToken == null) {
        return true;
    }

    if (tokenExpirationValidation && idpToken.isExpired()) {
        LOG.info("[IDP_TOKEN=" + idpToken.getId() + "] is expired.");
        return true;
    }

    return false;
}
 
Example 11
Source Project: cas4.0.x-server-wechat   Source File: ClientAction.java    License: 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 12
Source Project: shibboleth-oidc   Source File: InitializeLoginAction.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
protected Event doExecute(@Nonnull final RequestContext springRequestContext,
                          @Nonnull final ProfileRequestContext profileRequestContext) {
    log.debug("{} Initializing login action", getLogPrefix());
    final HttpServletRequest request = OIDCUtils.getHttpServletRequest(springRequestContext);
    if (request == null) {
        throw new OIDCException("HttpServletRequest cannot be null");
    }

    final HttpServletResponse response = OIDCUtils.getHttpServletResponse(springRequestContext);
    if (response == null) {
        throw new OIDCException("HttpServletRequest cannot be null");
    }
    HttpServletRequestResponseContext.loadCurrent(request, response);
    return Events.Success.event(this);
}
 
Example 13
/**
 * 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 14
Source Project: cas-mfa   Source File: SendTicketGrantingTicketAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Event doExecute(final RequestContext context) {

    final MultiFactorCredentials mfa = MultiFactorRequestContextUtils.getMfaCredentials(context);

    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final String ticketGrantingTicketValueFromCookie = (String) context.getFlowScope().get("ticketGrantingTicketId");

    if (ticketGrantingTicketId == null) {
        return success();
    }

    this.ticketGrantingTicketCookieGenerator.addCookie(WebUtils.getHttpServletRequest(context), WebUtils
            .getHttpServletResponse(context), ticketGrantingTicketId);

    if ((mfa == null || this.destroyPreviousSSOSession)
            && ticketGrantingTicketValueFromCookie != null
            && !ticketGrantingTicketId.equals(ticketGrantingTicketValueFromCookie)) {
        logger.debug("Destroying the previous SSO session mapped to [{}] because, this is not an MFA request,"
                + " or configuration dictated destroying the SSO session.", ticketGrantingTicketValueFromCookie);
        this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketValueFromCookie);
    }

    return success();
}
 
Example 15
/**
 * 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 16
Source Project: cxf-fediz   Source File: WebUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * remove attribute from request and session.
 *
 * @param context
 * @param attributeKey
 * @return the removed attribute
 */
public static Object removeAttribute(final RequestContext context,
        final String attributeKey) {
    Object valueReq = removeAttributeFromRequestScope(context, attributeKey);
    Object valueSes = removeAttributeFromExternalContext(context,
            attributeKey);
    if (valueSes != null) {
        return valueSes; // not clean if request has different value !
    }
    if (valueReq != null) {
        return valueReq;
    }
    return null;
}
 
Example 17
/**
 * Determines whether the TGT in the flow request context is valid.
 *
 * @param requestContext Flow request context.
 *
 * @return {@link #NOT_EXISTS}, {@link #INVALID}, or {@link #VALID}.
 */
public Event checkValidity(final RequestContext requestContext) {

    final String tgtId = WebUtils.getTicketGrantingTicketId(requestContext);
    if (!StringUtils.hasText(tgtId)) {
        return new Event(this, NOT_EXISTS);
    }

    final Ticket ticket = this.ticketRegistry.getTicket(tgtId);
    return new Event(this, ticket != null && !ticket.isExpired() ? VALID : INVALID);
}
 
Example 18
Source Project: cxf-fediz   Source File: WebUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void removeCookie(
        final RequestContext context, final String cookieName) {
    HttpServletResponse httpServletResponse = getHttpServletResponse(context);
    Cookie cookie = readCookie(context, cookieName);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setValue("");
        httpServletResponse.addCookie(cookie);
    }
}
 
Example 19
Source Project: CAS   Source File: ValidateLoginAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Event doExecute(RequestContext context) throws Exception {
    CustomCredential credential = (CustomCredential) WebUtils.getCredential(context);

    System.out.println("excute");

    //系统信息不为空才检测校验码
    if (credential instanceof CustomCredential) {

        String email = credential.getEmail();
        String telephone = credential.getTelephone();
        String capcha = credential.getCapcha();



        if (capcha.equals("") || capcha == null) {
            return getError(context, CAPTCHA_CODE);
        }

        if (email.equals("") || email == null) {
            return getError(context, EMAIL_CODE);
        }

        if (telephone.equals("") || telephone == null) {
            return getError(context, TELEPHONE_CODE);
        }

    }
    return null;
}
 
Example 20
Source Project: pizzeria   Source File: AssembleOrderAction.java    License: MIT License 5 votes vote down vote up
@Override
protected Event doExecute(RequestContext context) throws Exception {
    Customer customer = context.getFlowScope().get("customer", Customer.class);
    DeliveryAddress deliveryAddress = context.getFlowScope().get("deliveryAddress", DeliveryAddress.class);

    Order order = new Order();
    order.setOrderItems(ImmutableList.copyOf(cart.getOrderItems()));
    order.getOrderItems().forEach(orderItem -> orderItem.setOrder(order));
    order.setCustomer(customer);
    customer.getOrders().add(order);

    OrderEvent orderEvent = new OrderEvent();
    orderEvent.setOrderEventType(OrderEventType.CREATED);
    orderEvent.setOccurredOn(Instant.now());
    order.getOrderEvents().add(orderEvent);

    Boolean deliveryRequired = context.getFlowScope().getBoolean("deliveryRequired");

    if (deliveryRequired) {
        Delivery delivery = new Delivery();
        delivery.setDeliveryAddress(deliveryAddress);
        delivery.setOrder(order);
        delivery.setStatus(DeliveryStatus.PENDING);

        order.setDelivery(delivery);
    }

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

    return success();
}
 
Example 21
Source Project: CAS   Source File: ValidateLoginAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Event doExecute(RequestContext context) throws Exception {
    CustomCredential credential = (CustomCredential) WebUtils.getCredential(context);

    System.out.println("excute");

    //系统信息不为空才检测校验码
    if (credential instanceof CustomCredential) {

        String email = credential.getEmail();
        String telephone = credential.getTelephone();
        String capcha = credential.getCapcha();



        if (capcha.equals("") || capcha == null) {
            return getError(context, CAPTCHA_CODE);
        }

        if (email.equals("") || email == null) {
            return getError(context, EMAIL_CODE);
        }

        if (telephone.equals("") || telephone == null) {
            return getError(context, TELEPHONE_CODE);
        }

    }
    return null;
}
 
Example 22
/**
 * In the event of an MFA request, authenticate the credentials by default, and place
 * the authentication context back into the flow.
 * <p>Coming from the 'doAuthentication' and checking if the principal mfa source has been ranked or not
 * Or if coming straight from initial transition. In either case, if there is no mfa service already in the flow scope
 * try to get the principal attribute sourced mfa request and re-rank the existing mfa tx, so the mfa service is
 * always available in the flow scope for downstream subflows.
 * <p>If we get to this method, the mfa transaction is guaranteed to be in the flow scope.
 *
 * @param context request context
 * @param credentials the requesting credentials
 * @param messageContext the message bundle manager
 * @param id the identifier of the credential, based on implementation provided in the flow setup.
 *
 * @return the resulting event
 *
 * @throws Exception the exception
 */
protected final Event doMultiFactorAuthentication(final RequestContext context, final Credential credentials,
                                                  final MessageContext messageContext, final String id) throws Exception {

    Assert.notNull(id);
    Assert.notNull(credentials);

    try {
        final Authentication auth = this.authenticationManager.authenticate(credentials);
        if (MultiFactorRequestContextUtils.getMultifactorWebApplicationService(context) == null) {
            final List<MultiFactorAuthenticationRequestContext> mfaRequest =
                    getMfaRequestOrNull(auth, WebUtils.getService(context), context);
            //No principal attribute sourced mfa method request. Just get the highest ranked mfa service from existing ones
            if (mfaRequest == null) {
                MultiFactorRequestContextUtils.setMultifactorWebApplicationService(context,
                        getHighestRankedMfaRequestFromMfaTransaction(context));
            } else {
                final MultiFactorAuthenticationSupportingWebApplicationService highestService =
                        addToMfaTransactionAndGetHighestRankedMfaRequest(mfaRequest, context);
                MultiFactorRequestContextUtils.setMultifactorWebApplicationService(context, highestService);
                MultiFactorRequestContextUtils.setRequiredAuthenticationMethod(context, highestService.getAuthenticationMethod());
            }
        }

        final Event result = multiFactorAuthenticationSuccessful(auth, context, credentials, messageContext, id);
        MultiFactorRequestContextUtils.setAuthentication(context, auth);
        return result;
    } catch (final AuthenticationException e) {
        populateErrorsInstance(e.getMessage(), messageContext);
        MultiFactorRequestContextUtils.setAuthenticationExceptionInFlowScope(context, e);
        logger.error(e.getMessage(), e);
    }
    return getErrorEvent(context);
}
 
Example 23
Source Project: cxf-fediz   Source File: WebUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * get attribute from request; if not found get it from session.
 *
 * @param context
 * @param attributeKey
 * @return the attribute from the request or session
 */
public static Object getAttribute(final RequestContext context,
        final String attributeKey) {
    Object value = getAttributeFromRequestScope(context, attributeKey);
    if (value != null) {
        return value;
    }
    return getAttributeFromExternalContext(context, attributeKey);
}
 
Example 24
Source Project: springboot-shiro-cas-mybatis   Source File: WebUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Gets the http servlet request from the context.
 *
 * @param context the context
 * @return the http servlet request
 */
public static HttpServletRequest getHttpServletRequest(
    final RequestContext context) {
    Assert.isInstanceOf(ServletExternalContext.class, context
        .getExternalContext(),
        "Cannot obtain HttpServletRequest from event of type: "
            + context.getExternalContext().getClass().getName());

    return (HttpServletRequest) context.getExternalContext().getNativeRequest();
}
 
Example 25
Source Project: cxf-fediz   Source File: WebUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void addCookie(
        final RequestContext context, final String cookieName, final String cookieValue) {
    HttpServletResponse httpServletResponse = getHttpServletResponse(context);
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setSecure(true);
    cookie.setMaxAge(-1);
    cookie.setHttpOnly(true);
    cookie.setPath("/fediz-idp");
    httpServletResponse.addCookie(cookie);
}
 
Example 26
@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 27
Source Project: cxf-fediz   Source File: AuthnRequestParser.java    License: Apache License 2.0 5 votes vote down vote up
private void checkDestination(RequestContext context, RequestAbstractType request) throws ProcessingException {
    // Check destination
    String destination = request.getDestination();
    LOG.debug("Validating destination: {}", destination);

    String localAddr = WebUtils.getHttpServletRequest(context).getRequestURL().toString();
    if (destination == null || !localAddr.startsWith(destination)) {
        LOG.debug("The destination {} does not match the local address {}", destination, localAddr);
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }
}
 
Example 28
Source Project: cxf-fediz   Source File: WebUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpServletResponse getHttpServletResponse(
        final RequestContext context) {
    Object response =  context.getExternalContext().getNativeResponse();
    Assert.isInstanceOf(HttpServletResponse.class,
            response,
            "Cannot obtain HttpServletResponse from event of type: "
                    + context.getExternalContext().getClass().getName());
    return (HttpServletResponse) response;
}
 
Example 29
Source Project: springboot-shiro-cas-mybatis   Source File: WebUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Gets credential from the context.
 *
 * @param context the context
 * @return the credential, or null if it cant be found in the context or if it has no id.
 */
public static Credential getCredential(@NotNull final RequestContext context) {
    final Credential cFromRequest = (Credential) context.getRequestScope().get("credential");
    final Credential cFromFlow = (Credential) context.getFlowScope().get("credential");

    final Credential credential = cFromRequest != null ? cFromRequest : cFromFlow;
    if (credential != null && StringUtils.isBlank(credential.getId())) {
        return null;
    }
    return credential;
}
 
Example 30
@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final String openidIdentityParameter = context.getRequestParameters().get(OpenIdConstants.OPENID_IDENTITY);
    String userName = null;
    if (OpenIdConstants.OPENID_IDENTIFIERSELECT.equals(openidIdentityParameter)) {
        userName = OpenIdConstants.OPENID_IDENTIFIERSELECT;
        context.getExternalContext().getSessionMap().remove(OpenIdConstants.OPENID_LOCALID);
        // already authenticated: retrieve the username from the authentication
        if (ticketGrantingTicketId != null) {
            try {
                final TicketGrantingTicket tgt = getCentralAuthenticationService()
                        .getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
                userName = tgt.getAuthentication().getPrincipal().getId();
            } catch (final InvalidTicketException e) {
                logger.error("Cannot get TGT", e);
            }
        }
    } else {
        userName = this.extractor.extractLocalUsernameFromUri(openidIdentityParameter);
        context.getExternalContext().getSessionMap().put(OpenIdConstants.OPENID_LOCALID, userName);
    }
    final Service service = WebUtils.getService(context);

    // clear the service because otherwise we can fake the username
    if (service instanceof OpenIdService && userName == null) {
        context.getFlowScope().remove("service");
    }

    if (ticketGrantingTicketId == null || userName == null) {
        return null;
    }

    return new OpenIdCredential(
            ticketGrantingTicketId, userName);
}