Search in sources :

Example 11 with RequestContext

use of org.springframework.webflow.execution.RequestContext in project cas by apereo.

the class RegisteredServiceThemeBasedViewResolver method loadView.

@Override
protected View loadView(final String viewName, final Locale locale) throws Exception {
    final View view = super.loadView(viewName, locale);
    final RequestContext requestContext = RequestContextHolder.getRequestContext();
    final WebApplicationService service;
    final HttpServletResponse response;
    final List<ArgumentExtractor> argumentExtractorList = Collections.singletonList(this.argumentExtractor);
    if (requestContext != null) {
        response = WebUtils.getHttpServletResponse(requestContext);
        service = WebUtils.getService(argumentExtractorList, requestContext);
    } else {
        final HttpServletRequest request = WebUtils.getHttpServletRequestFromRequestAttributes();
        service = WebUtils.getService(argumentExtractorList, request);
        response = WebUtils.getHttpServletResponseFromRequestAttributes();
    }
    if (service == null) {
        return view;
    }
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    if (registeredService != null) {
        try {
            RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(service, registeredService);
        } catch (final Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
    }
    if (registeredService != null && StringUtils.hasText(registeredService.getTheme()) && view instanceof AbstractThymeleafView) {
        LOGGER.debug("Attempting to locate views for service [{}] with theme [{}]", registeredService.getServiceId(), registeredService.getTheme());
        final AbstractThymeleafView thymeleafView = (AbstractThymeleafView) view;
        final String viewUrl = registeredService.getTheme() + '/' + thymeleafView.getTemplateName();
        final String viewLocationUrl = prefix.concat(viewUrl).concat(suffix);
        LOGGER.debug("Attempting to locate view at [{}]", viewLocationUrl);
        final TemplateLocation location = new TemplateLocation(viewLocationUrl);
        if (location.exists(getApplicationContext())) {
            LOGGER.debug("Found view [{}]", viewUrl);
            thymeleafView.setTemplateName(viewUrl);
        } else {
            LOGGER.debug("View [{}] does not exist. Falling back to default view at [{}]", viewLocationUrl, thymeleafView.getTemplateName());
        }
    }
    return view;
}
Also used : ArgumentExtractor(org.apereo.cas.web.support.ArgumentExtractor) HttpServletRequest(javax.servlet.http.HttpServletRequest) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) RegisteredService(org.apereo.cas.services.RegisteredService) TemplateLocation(org.springframework.boot.autoconfigure.template.TemplateLocation) AbstractThymeleafView(org.thymeleaf.spring4.view.AbstractThymeleafView) HttpServletResponse(javax.servlet.http.HttpServletResponse) RequestContext(org.springframework.webflow.execution.RequestContext) AbstractThymeleafView(org.thymeleaf.spring4.view.AbstractThymeleafView) View(org.springframework.web.servlet.View)

Example 12 with RequestContext

use of org.springframework.webflow.execution.RequestContext in project cas by apereo.

the class YubiKeyAuthenticationHandlerTests method before.

@Before
public void before() {
    final RequestContext ctx = mock(RequestContext.class);
    when(ctx.getConversationScope()).thenReturn(new LocalAttributeMap<>());
    WebUtils.putAuthentication(CoreAuthenticationTestUtils.getAuthentication(), ctx);
    RequestContextHolder.setRequestContext(ctx);
}
Also used : RequestContext(org.springframework.webflow.execution.RequestContext) Before(org.junit.Before)

Example 13 with RequestContext

use of org.springframework.webflow.execution.RequestContext in project uPortal by Jasig.

the class PersonQueryValidator method validatePersonLookup.

/** Ensures all passed attributes are part of the valid query attribute set. */
public void validatePersonLookup(PersonQuery personQuery, MessageContext context) {
    final RequestContext requestContext = RequestContextHolder.getRequestContext();
    final ExternalContext externalContext = requestContext.getExternalContext();
    final Set<String> queryAttributes = personLookupHelper.getQueryAttributes(externalContext);
    final Map<String, Attribute> attributes = personQuery.getAttributes();
    for (final String attribute : attributes.keySet()) {
        if (!queryAttributes.contains(attribute)) {
            final MessageBuilder messageBuilder = new MessageBuilder();
            messageBuilder.error();
            messageBuilder.source("attributes[" + attribute + "].value");
            messageBuilder.code("personLookup.invalidQueryAttribute");
            messageBuilder.arg(attribute);
            final MessageResolver errorMessage = messageBuilder.build();
            context.addMessage(errorMessage);
        }
    }
}
Also used : MessageResolver(org.springframework.binding.message.MessageResolver) MessageBuilder(org.springframework.binding.message.MessageBuilder) Attribute(org.apereo.portal.portlets.Attribute) ExternalContext(org.springframework.webflow.context.ExternalContext) RequestContext(org.springframework.webflow.execution.RequestContext)

Example 14 with RequestContext

use of org.springframework.webflow.execution.RequestContext in project cas by apereo.

the class GoogleAuthenticatorAuthenticationHandler method doAuthentication.

@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final GoogleAuthenticatorTokenCredential tokenCredential = (GoogleAuthenticatorTokenCredential) credential;
    if (!NumberUtils.isCreatable(tokenCredential.getToken())) {
        throw new PreventedException("Invalid non-numeric OTP format specified.", new IllegalArgumentException("Invalid token " + tokenCredential.getToken()));
    }
    final int otp = Integer.parseInt(tokenCredential.getToken());
    LOGGER.debug("Received OTP [{}]", otp);
    final RequestContext context = RequestContextHolder.getRequestContext();
    if (context == null) {
        new IllegalArgumentException("No request context could be found to locate an authentication event");
    }
    final Authentication authentication = WebUtils.getAuthentication(context);
    if (authentication == null) {
        new IllegalArgumentException("Request context has no reference to an authentication event to locate a principal");
    }
    final String uid = authentication.getPrincipal().getId();
    LOGGER.debug("Received principal id [{}]", uid);
    final String secKey = this.credentialRepository.getSecret(uid);
    if (StringUtils.isBlank(secKey)) {
        throw new AccountNotFoundException(uid + " cannot be found in the registry");
    }
    if (this.tokenRepository.exists(uid, otp)) {
        throw new AccountExpiredException(uid + " cannot reuse OTP " + otp + " as it may be expired/invalid");
    }
    final boolean isCodeValid = this.googleAuthenticatorInstance.authorize(secKey, otp);
    if (isCodeValid) {
        this.tokenRepository.store(new GoogleAuthenticatorToken(otp, uid));
        return createHandlerResult(tokenCredential, this.principalFactory.createPrincipal(uid), null);
    }
    throw new FailedLoginException("Failed to authenticate code " + otp);
}
Also used : FailedLoginException(javax.security.auth.login.FailedLoginException) Authentication(org.apereo.cas.authentication.Authentication) AccountExpiredException(javax.security.auth.login.AccountExpiredException) GoogleAuthenticatorToken(org.apereo.cas.adaptors.gauth.repository.token.GoogleAuthenticatorToken) PreventedException(org.apereo.cas.authentication.PreventedException) RequestContext(org.springframework.webflow.execution.RequestContext) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException)

Example 15 with RequestContext

use of org.springframework.webflow.execution.RequestContext in project cas by apereo.

the class ServiceThemeResolver method resolveThemeName.

@Override
public String resolveThemeName(final HttpServletRequest request) {
    if (this.servicesManager == null) {
        return getDefaultThemeName();
    }
    // retrieve the user agent string from the request
    final String userAgent = WebUtils.getHttpServletRequestUserAgent(request);
    if (StringUtils.isBlank(userAgent)) {
        return getDefaultThemeName();
    }
    overrides.entrySet().stream().filter(entry -> entry.getKey().matcher(userAgent).matches()).findFirst().ifPresent(entry -> {
        request.setAttribute("isMobile", "true");
        request.setAttribute("browserType", entry.getValue());
    });
    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();
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) RequestContext(org.springframework.webflow.execution.RequestContext)

Aggregations

RequestContext (org.springframework.webflow.execution.RequestContext)24 WebUtils (org.apereo.cas.web.support.WebUtils)8 Event (org.springframework.webflow.execution.Event)8 RegisteredService (org.apereo.cas.services.RegisteredService)7 Logger (org.slf4j.Logger)7 LoggerFactory (org.slf4j.LoggerFactory)7 Map (java.util.Map)6 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 Authentication (org.apereo.cas.authentication.Authentication)6 FailedLoginException (javax.security.auth.login.FailedLoginException)5 Principal (org.apereo.cas.authentication.principal.Principal)5 MultifactorAuthenticationProvider (org.apereo.cas.services.MultifactorAuthenticationProvider)5 ServicesManager (org.apereo.cas.services.ServicesManager)5 Optional (java.util.Optional)4 Set (java.util.Set)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 StringUtils (org.apache.commons.lang3.StringUtils)4 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)4 AuthenticationServiceSelectionPlan (org.apereo.cas.authentication.AuthenticationServiceSelectionPlan)4 AuthenticationSystemSupport (org.apereo.cas.authentication.AuthenticationSystemSupport)4