Search in sources :

Example 26 with View

use of org.springframework.web.servlet.View in project cas by apereo.

the class OAuth20AuthorizeControllerTests method verifyCodeRedirectToClientApproved.

@Test
public void verifyCodeRedirectToClientApproved() throws Exception {
    clearAllServices();
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuthConstants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.RESPONSE_TYPE, OAuth20ResponseTypes.CODE.name().toLowerCase());
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    mockRequest.setParameter(OAuthConstants.BYPASS_APPROVAL_PROMPT, "true");
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
    service.setBypassApprovalPrompt(false);
    oAuth20AuthorizeEndpointController.getServicesManager().save(service);
    final CasProfile profile = new CasProfile();
    profile.setId(ID);
    final Map<String, Object> attributes = new HashMap<>();
    attributes.put(FIRST_NAME_ATTRIBUTE, FIRST_NAME);
    attributes.put(LAST_NAME_ATTRIBUTE, LAST_NAME);
    profile.addAttributes(attributes);
    final MockHttpSession session = new MockHttpSession();
    mockRequest.setSession(session);
    session.putValue(Pac4jConstants.USER_PROFILES, profile);
    final ModelAndView modelAndView = oAuth20AuthorizeEndpointController.handleRequestInternal(mockRequest, mockResponse);
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    final String redirectUrl = redirectView.getUrl();
    assertTrue(redirectUrl.startsWith(REDIRECT_URI + "?code=OC-"));
    final String code = StringUtils.substringAfter(redirectUrl, "?code=");
    final OAuthCode oAuthCode = (OAuthCode) oAuth20AuthorizeEndpointController.getTicketRegistry().getTicket(code);
    assertNotNull(oAuthCode);
    final Principal principal = oAuthCode.getAuthentication().getPrincipal();
    assertEquals(ID, principal.getId());
    final Map<String, Object> principalAttributes = principal.getAttributes();
    assertEquals(attributes.size(), principalAttributes.size());
    assertEquals(FIRST_NAME, principalAttributes.get(FIRST_NAME_ATTRIBUTE));
}
Also used : CasProfile(org.pac4j.cas.profile.CasProfile) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ModelAndView(org.springframework.web.servlet.ModelAndView) OAuthCode(org.apereo.cas.ticket.code.OAuthCode) RedirectView(org.springframework.web.servlet.view.RedirectView) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View) RedirectView(org.springframework.web.servlet.view.RedirectView) MockHttpSession(org.springframework.mock.web.MockHttpSession) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Principal(org.apereo.cas.authentication.principal.Principal) Test(org.junit.Test)

Example 27 with View

use of org.springframework.web.servlet.View in project cas by apereo.

the class Cas20ResponseViewTests method verifyView.

@Test
public void verifyView() throws Exception {
    final ModelAndView modelAndView = this.getModelAndViewUponServiceValidationWithSecurePgtUrl();
    final MockHttpServletRequest req = new MockHttpServletRequest(new MockServletContext());
    req.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, new GenericWebApplicationContext(req.getServletContext()));
    final MockHttpServletResponse resp = new MockHttpServletResponse();
    final View delegatedView = new View() {

        @Override
        public String getContentType() {
            return "text/html";
        }

        @Override
        public void render(final Map<String, ?> map, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
            map.forEach(request::setAttribute);
        }
    };
    final Cas20ResponseView view = new Cas20ResponseView(true, null, null, "attribute", delegatedView);
    view.render(modelAndView.getModel(), req, resp);
    assertNotNull(req.getAttribute(CasViewConstants.MODEL_ATTRIBUTE_NAME_CHAINED_AUTHENTICATIONS));
    assertNotNull(req.getAttribute(CasViewConstants.MODEL_ATTRIBUTE_NAME_PRIMARY_AUTHENTICATION));
    assertNotNull(req.getAttribute(CasViewConstants.MODEL_ATTRIBUTE_NAME_PRINCIPAL));
    assertNotNull(req.getAttribute(CasProtocolConstants.VALIDATION_CAS_MODEL_PROXY_GRANTING_TICKET_IOU));
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) HttpServletResponse(javax.servlet.http.HttpServletResponse) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View) Map(java.util.Map) MockServletContext(org.springframework.mock.web.MockServletContext) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 28 with View

use of org.springframework.web.servlet.View in project cas by apereo.

the class Cas30ResponseViewTests method renderView.

private Map<?, ?> renderView() throws Exception {
    final ModelAndView modelAndView = this.getModelAndViewUponServiceValidationWithSecurePgtUrl();
    final MockHttpServletRequest req = new MockHttpServletRequest(new MockServletContext());
    req.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, new GenericWebApplicationContext(req.getServletContext()));
    final ProtocolAttributeEncoder encoder = new DefaultCasProtocolAttributeEncoder(this.servicesManager, NoOpCipherExecutor.getInstance());
    final View viewDelegated = new View() {

        @Override
        public String getContentType() {
            return MediaType.TEXT_HTML_VALUE;
        }

        @Override
        public void render(final Map<String, ?> map, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
            map.forEach(request::setAttribute);
        }
    };
    final Cas30ResponseView view = new Cas30ResponseView(true, encoder, servicesManager, "attribute", viewDelegated, true);
    final MockHttpServletResponse resp = new MockHttpServletResponse();
    view.render(modelAndView.getModel(), req, resp);
    return (Map<?, ?>) req.getAttribute(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View) MockServletContext(org.springframework.mock.web.MockServletContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) DefaultCasProtocolAttributeEncoder(org.apereo.cas.authentication.support.DefaultCasProtocolAttributeEncoder) DefaultCasProtocolAttributeEncoder(org.apereo.cas.authentication.support.DefaultCasProtocolAttributeEncoder) ProtocolAttributeEncoder(org.apereo.cas.authentication.ProtocolAttributeEncoder) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext) Map(java.util.Map) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 29 with View

use of org.springframework.web.servlet.View 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 30 with View

use of org.springframework.web.servlet.View in project grails-core by grails.

the class GroovyPageViewResolver method loadView.

@Override
protected View loadView(String viewName, Locale locale) throws Exception {
    Assert.notNull(templateEngine, "Property [templateEngine] cannot be null");
    if (viewName.endsWith(GSP_SUFFIX)) {
        viewName = viewName.substring(0, viewName.length() - GSP_SUFFIX.length());
    }
    if (!allowGrailsViewCaching) {
        return createGrailsView(viewName);
    }
    String viewCacheKey = groovyPageLocator.resolveViewFormat(viewName);
    String currentControllerKeyPrefix = resolveCurrentControllerKeyPrefixes();
    if (currentControllerKeyPrefix != null) {
        viewCacheKey = currentControllerKeyPrefix + ':' + viewCacheKey;
    }
    CacheEntry<View> entry = viewCache.get(viewCacheKey);
    final String lookupViewName = viewName;
    Callable<View> updater = new Callable<View>() {

        public View call() throws Exception {
            try {
                return createGrailsView(lookupViewName);
            } catch (Exception e) {
                throw new WrappedInitializationException(e);
            }
        }
    };
    View view = null;
    if (entry == null) {
        try {
            return CacheEntry.getValue(viewCache, viewCacheKey, cacheTimeout, updater);
        } catch (CacheEntry.UpdateException e) {
            e.rethrowCause();
            // make compiler happy
            return null;
        }
    }
    try {
        view = entry.getValue(cacheTimeout, updater, true, null);
    } catch (WrappedInitializationException e) {
        e.rethrowCause();
    }
    return view;
}
Also used : CacheEntry(grails.util.CacheEntry) View(org.springframework.web.servlet.View) AbstractUrlBasedView(org.springframework.web.servlet.view.AbstractUrlBasedView) Callable(java.util.concurrent.Callable)

Aggregations

View (org.springframework.web.servlet.View)71 Test (org.junit.Test)51 ModelAndView (org.springframework.web.servlet.ModelAndView)19 HashMap (java.util.HashMap)18 RedirectView (org.springframework.web.servlet.view.RedirectView)18 Locale (java.util.Locale)17 ViewResolver (org.springframework.web.servlet.ViewResolver)17 HttpServletResponse (javax.servlet.http.HttpServletResponse)13 MockServletContext (org.springframework.mock.web.test.MockServletContext)13 StaticWebApplicationContext (org.springframework.web.context.support.StaticWebApplicationContext)13 Map (java.util.Map)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)12 MockHttpServletResponse (org.springframework.mock.web.test.MockHttpServletResponse)11 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)10 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 MockHttpServletRequest (org.springframework.mock.web.test.MockHttpServletRequest)10 MediaType (org.springframework.http.MediaType)7 ContentNegotiationManager (org.springframework.web.accept.ContentNegotiationManager)7 Principal (org.apereo.cas.authentication.principal.Principal)6 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)6