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

The following examples show how to use org.jasig.cas.web.support.WebUtils#getService() . 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: InitiatingMultiFactorAuthenticationViaFormActionTests.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessfulMfaAuthentication() throws Exception {
    final String id = MultiFactorAuthenticationSpringWebflowEventBuilder.MFA_EVENT_ID_PREFIX
            + AUTHN_METHOD;
    final TransitionDefinition def = mock(TransitionDefinition.class);
    when(def.getId()).thenReturn(id);

    when(this.ctx.getMatchingTransition(anyString())).thenReturn(def);

    final Event ev = this.action.doExecute(this.ctx);
    assertNotNull(ev);
    final MultiFactorAuthenticationSupportingWebApplicationService svc =
            (MultiFactorAuthenticationSupportingWebApplicationService) WebUtils.getService(this.ctx);
    assertNotNull(svc);

    assertEquals(ev.getId(), id);
}
 
Example 2
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 3
Source File: ServiceAuthenticationMethodMultiFactorAuthenticationSpringWebflowEventBuilder.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Override
public Event buildEvent(final RequestContext context) {
    final MultiFactorAuthenticationSupportingWebApplicationService service = (MultiFactorAuthenticationSupportingWebApplicationService)
            WebUtils.getService(context);

    logger.debug("Attempting to build an event based on the authentication method [{}] and service [{}]",
            service.getAuthenticationMethod(), service.getId());
    final Event event = new Event(this, MFA_EVENT_ID_PREFIX + service.getAuthenticationMethod());
    logger.debug("Resulting event id is [{}]. Locating transitions in the context for that event id...",
            event.getId());

    final TransitionDefinition def = context.getMatchingTransition(event.getId());
    if (def == null) {
        logger.warn("Transition definition cannot be found for event [{}]", event.getId());
        throw new UnrecognizedAuthenticationMethodException(service.getAuthenticationMethod(), service.getId());
    }
    logger.debug("Found matching transition [{}] with target [{}] for event {}. Will proceed normally..",
        def.getId(), def.getTargetStateId(), event.getId());

    return event;
}
 
Example 4
Source File: RememberAuthenticationMethodMetaDataPopulator.java    From cas-mfa with Apache License 2.0 6 votes vote down vote up
@Override
public void populateAttributes(final AuthenticationBuilder authenticationBuilder, final Credential credential) {
    final RequestContext context = RequestContextHolder.getRequestContext();
    if (context != null) {
        final Service svc = WebUtils.getService(context);

        if (svc instanceof MultiFactorAuthenticationSupportingWebApplicationService) {
            final MultiFactorAuthenticationSupportingWebApplicationService mfaSvc =
                    (MultiFactorAuthenticationSupportingWebApplicationService) svc;

            authenticationBuilder.addAttribute(
                    MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD,
                    mfaSvc.getAuthenticationMethod());

            logger.debug("Captured authentication method [{}] into the authentication context",
                    mfaSvc.getAuthenticationMethod());
        }
    }
}
 
Example 5
Source File: OpenIdSingleSignOnAction.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 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 6
Source File: ServiceThemeResolver.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
public String resolveThemeName(final HttpServletRequest request) {
    if (this.servicesManager == null) {
        return getDefaultThemeName();
    }
    // retrieve the user agent string from the request
    final String userAgent = request.getHeader("User-Agent");

    if (StringUtils.isBlank(userAgent)) {
        return getDefaultThemeName();
    }

    for (final Map.Entry<Pattern, String> entry : this.overrides.entrySet()) {
        if (entry.getKey().matcher(userAgent).matches()) {
            request.setAttribute("isMobile", "true");
            request.setAttribute("browserType", entry.getValue());
            break;
        }
    }

    final RequestContext context = RequestContextHolder.getRequestContext();
    final Service service = WebUtils.getService(context);
    if (service != null) {
        final RegisteredService rService = this.servicesManager.findServiceBy(service);
        if (rService != null && rService.getAccessStrategy().isServiceAccessAllowed()
                && StringUtils.isNotBlank(rService.getTheme())) {
            LOGGER.debug("Service [{}] is configured to use a custom theme [{}]", rService, rService.getTheme());
            final CasThemeResourceBundleMessageSource messageSource = new CasThemeResourceBundleMessageSource();
            messageSource.setBasename(rService.getTheme());
            if (messageSource.doGetBundle(rService.getTheme(), request.getLocale()) != null) {
                LOGGER.debug("Found custom theme [{}] for service [{}]", rService.getTheme(), rService);
                return rService.getTheme();
            } else {
                LOGGER.warn("Custom theme {} for service {} cannot be located. Falling back to default theme...",
                        rService.getTheme(), rService);
            }
        }
    }
    return getDefaultThemeName();
}
 
Example 7
Source File: ConfigurableUserAgentOverrideThemeResolver.java    From uPortal-start with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve the theme for the service. This method's logic is taken from ServiceThemeResolver.
 *
 * @param request
 * @return configured theme for this service
 */
protected String resolveServiceThemeName(HttpServletRequest request) {
    if (this.servicesManager == null) {
        return getDefaultThemeName();
    }

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

    final RegisteredService rService = this.servicesManager.findServiceBy(service);

    return service != null && rService != null && StringUtils.hasText(rService.getTheme())
            ? rService.getTheme()
            : getDefaultThemeName();
}
 
Example 8
Source File: ServiceThemeResolver.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Override
public String resolveThemeName(final HttpServletRequest request) {
    if (this.servicesManager == null) {
        return getDefaultThemeName();
    }

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

    final RegisteredService rService = this.servicesManager.findServiceBy(service);

    // retrieve the user agent string from the request
    String userAgent = request.getHeader("User-Agent");

    if (userAgent == null) {
        return getDefaultThemeName();
    }

    for (final Map.Entry<Pattern, String> entry : this.overrides.entrySet()) {
        if (entry.getKey().matcher(userAgent).matches()) {
            request.setAttribute("isMobile", "true");
            request.setAttribute("browserType", entry.getValue());
            break;
        }
    }

    return service != null && rService != null && StringUtils.hasText(rService.getTheme())
            ? rService.getTheme() : getDefaultThemeName();
}
 
Example 9
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 10
Source File: GatewayServicesManagementCheck.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 Service service = WebUtils.getService(context);

    final boolean match = this.servicesManager.matchesExistingService(service);

    if (match) {
        return success();
    }

    final String msg = String.format("ServiceManagement: Unauthorized Service Access. "
            + "Service [%s] does not match entries in service registry.", service.getId());
    logger.warn(msg);
    throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
}
 
Example 11
Source File: WebUtilTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testFoundNoService() {
    final SamlArgumentExtractor openIdArgumentExtractor = new SamlArgumentExtractor();
    final ArgumentExtractor[] argumentExtractors = new ArgumentExtractor[] {
            openIdArgumentExtractor};
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("service", "test");

    final Service service = WebUtils.getService(Arrays
            .asList(argumentExtractors), request);

    assertNull(service);
}
 
Example 12
Source File: WebUtilTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindService() {
    final SamlArgumentExtractor openIdArgumentExtractor = new SamlArgumentExtractor();
    final CasArgumentExtractor casArgumentExtractor = new CasArgumentExtractor();
    final ArgumentExtractor[] argumentExtractors = new ArgumentExtractor[] {
            openIdArgumentExtractor, casArgumentExtractor};
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("service", "test");

    final Service service = WebUtils.getService(Arrays
            .asList(argumentExtractors), request);

    assertEquals("test", service.getId());
}
 
Example 13
Source File: AuthenticationViaFormAction.java    From taoshop with Apache License 2.0 5 votes vote down vote up
/**
 * Is request asking for service ticket?
 *
 * @param context the context
 * @return true, if both service and tgt are found, and the request is not asking to renew.
 * @since 4.1.0
 */
protected boolean isRequestAskingForServiceTicket(final RequestContext context) {
    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final Service service = WebUtils.getService(context);
    return (StringUtils.isNotBlank(context.getRequestParameters().get(CasProtocolConstants.PARAMETER_RENEW))
            && ticketGrantingTicketId != null
            && service != null);
}
 
Example 14
Source File: RegisteredServiceThemeBasedViewResolver.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Uses the viewName and the theme associated with the service.
 * being requested and returns the appropriate view.
 * @param viewName the name of the view to be resolved
 * @return a theme-based UrlBasedView
 * @throws Exception an exception
 */
@Override
protected AbstractUrlBasedView buildView(final String viewName) throws Exception {
    final RequestContext requestContext = RequestContextHolder.getRequestContext();
    final WebApplicationService service = WebUtils.getService(requestContext);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    final String themeId = service != null && registeredService != null
            && registeredService.getAccessStrategy().isServiceAccessAllowed()
            && StringUtils.hasText(registeredService.getTheme()) ? registeredService.getTheme() : defaultThemeId;

    final String themePrefix = String.format("%s/%s/ui/", pathPrefix, themeId);
    LOGGER.debug("Prefix {} set for service {} with theme {}", themePrefix, service, themeId);

    //Build up the view like the base classes do, but we need to forcefully set the prefix for each request.
    //From UrlBasedViewResolver.buildView
    final InternalResourceView view = (InternalResourceView) BeanUtils.instantiateClass(getViewClass());
    view.setUrl(themePrefix + viewName + getSuffix());
    final String contentType = getContentType();
    if (contentType != null) {
        view.setContentType(contentType);
    }
    view.setRequestContextAttribute(getRequestContextAttribute());
    view.setAttributesMap(getAttributesMap());

    //From InternalResourceViewResolver.buildView
    view.setAlwaysInclude(false);
    view.setExposeContextBeansAsAttributes(false);
    view.setPreventDispatchLoop(true);

    LOGGER.debug("View resolved: {}", view.getUrl());

    return view;
}
 
Example 15
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 16
Source File: AuthenticationViaFormAction.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Is request asking for service ticket?
 *
 * @param context the context
 * @return true, if both service and tgt are found, and the request is not asking to renew.
 * @since 4.1.0
 */
protected boolean isRequestAskingForServiceTicket(final RequestContext context) {
    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final Service service = WebUtils.getService(context);
    return (StringUtils.isNotBlank(context.getRequestParameters().get(CasProtocolConstants.PARAMETER_RENEW))
            && ticketGrantingTicketId != null
            && service != null);
}
 
Example 17
Source File: GatewayServicesManagementCheck.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 Service service = WebUtils.getService(context);

    final boolean match = this.servicesManager.matchesExistingService(service);

    if (match) {
        return success();
    }

    final String msg = String.format("ServiceManagement: Unauthorized Service Access. "
            + "Service [%s] does not match entries in service registry.", service.getId());
    logger.warn(msg);
    throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
}
 
Example 18
Source File: OpenIdSingleSignOnAction.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@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);
}
 
Example 19
Source File: WebUtilTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyFoundNoService() {
    final SamlArgumentExtractor openIdArgumentExtractor = new SamlArgumentExtractor();
    final ArgumentExtractor[] argumentExtractors = new ArgumentExtractor[] {
            openIdArgumentExtractor};
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("service", "test");

    final Service service = WebUtils.getService(Arrays
            .asList(argumentExtractors), request);

    assertNull(service);
}
 
Example 20
Source File: WebUtilTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyFindService() {
    final SamlArgumentExtractor openIdArgumentExtractor = new SamlArgumentExtractor();
    final CasArgumentExtractor casArgumentExtractor = new CasArgumentExtractor();
    final ArgumentExtractor[] argumentExtractors = new ArgumentExtractor[] {
            openIdArgumentExtractor, casArgumentExtractor};
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setParameter("service", "test");

    final Service service = WebUtils.getService(Arrays
            .asList(argumentExtractors), request);

    assertEquals("test", service.getId());
}