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); }
@Bean public ViewResolver contentNegotiatingViewResolver() { logger.debug("Configuring the ContentNegotiatingViewResolver"); ContentNegotiatingViewResolver viewResolver = new ContentNegotiatingViewResolver(); List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>(); UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver(); urlBasedViewResolver.setViewClass(JstlView.class); urlBasedViewResolver.setSuffix(".html"); viewResolvers.add(urlBasedViewResolver); viewResolver.setViewResolvers(viewResolvers); List<View> defaultViews = new ArrayList<View>(); defaultViews.add(new MappingJackson2JsonView()); viewResolver.setDefaultViews(defaultViews); return viewResolver; }
@GetMapping public ModelAndView generateGradePDF(@RequestParam("identifier") String identifier, ModelMap modelMap, UriComponentsBuilder uriComponentsBuilder) throws Exception { View view = new GradePDFView(); Grade grade = gradeService.getForValidation(identifier); if (grade == null) { return new ModelAndView("error/404"); } modelMap.addAttribute("grade", grade); modelMap.addAttribute( "validationLink", uriComponentsBuilder .path("/public/grade") .queryParam("identifier", identifier) .build() .toString() ); ModelAndView modelAndView = new ModelAndView(view); return modelAndView; }
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public View uploadFile(@RequestParam("file") MultipartFile file) { try { InputStream input = file.getInputStream(); this.messageManagementService.importFromExcel(input); } catch (Exception e) { LOG.error("error on uploading messages", e); return new RedirectView("../files.html?uploadSuccess=no&message=" + e.getMessage().toString()); } return new RedirectView("../files.html?uploadSuccess=yes"); }
@PostMapping("topic") public View addAnswer(@RequestParam("content") String content, @RequestParam("code") String code, @RequestParam("id_topic") String id_topic, @RequestParam("id_user") String id_user, HttpServletRequest request) { Answer answer = new Answer(); answer.setContent(content); // I know that it can be blank field, but I did it on purpose to find out about Optionals: if (Objects.equals(code, "")) answer.setCode(null); else answer.setCode(code); answer.setCreatedDate(LocalDateTime.now()); answer.setUseful(false); answer.setTopic(topicRepository.findTopicById(Long.valueOf(id_topic))); answer.setUser(userRepository.getUserById(Long.parseLong(id_user))); answerRepository.save(answer); String contextPath = request.getContextPath(); return new RedirectView(contextPath + "/topic/" + id_topic); }
@PostMapping("profile") public View addTask(@RequestParam("category") String category, @RequestParam("title") String title, @RequestParam("content") String content, @RequestParam("code") String code, @RequestParam("id_user") String id_user, HttpServletRequest request) { Topic topic = new Topic(); topic.setCategory(category); // I know that it can be blank field, but I did it on purpose to find out about Optionals: if (Objects.equals(code, "")) topic.setCode(null); else topic.setCode(code); topic.setContent(content); topic.setTitle(title); topic.setCreatedDate(LocalDateTime.now()); topic.setUser(userRepository.getUserById(Long.parseLong(id_user))); topicRepository.save(topic); String contextPath = request.getContextPath(); return new RedirectView(contextPath + "/profile"); }
@PostMapping("register") public View registerUser(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("introduction") String introduction, HttpServletRequest request) { String contextPath = request.getContextPath(); User user = new User(); if (userRepository.getUserByUsername(username) == null) { user.setUsername(username); // I know that it can be blank field, but I did it on purpose to find out about Optionals: if (Objects.equals(introduction, "")) user.setIntroduction(null); else user.setIntroduction(introduction); user.setPassword(password); user.setPassword(passwordEncoder.encode(password)); user.setCreatedDate(LocalDateTime.now()); userRepository.save(user); return new RedirectView(contextPath + "/login"); } else return new RedirectView(contextPath + "/register"); }
@SuppressWarnings("unchecked") private ModelAndView getModelAndView(Object returnValue) { if (returnValue instanceof ModelAndView) { return (ModelAndView) returnValue; } else if (returnValue instanceof Model) { return new ModelAndView().addAllObjects(((Model) returnValue).asMap()); } else if (returnValue instanceof Map) { return new ModelAndView().addAllObjects((Map<String, Object>) returnValue); } else if (returnValue instanceof View) { return new ModelAndView(returnValue); } else if (returnValue instanceof String) { return new ModelAndView((String) returnValue); } else if (returnValue == null) { return new ModelAndView(); } else { throw new IllegalArgumentException("Invalid handler method return value: " + returnValue); } }
@Override public org.springframework.web.servlet.ModelAndView resolveModelAndView(Method handlerMethod, Class<?> handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) { if (returnValue instanceof MySpecialArg) { return new org.springframework.web.servlet.ModelAndView(new View() { @Override public String getContentType() { return "text/html"; } @Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.getWriter().write("myValue"); } }); } return UNRESOLVED; }
/** * Overridden to implement check for "redirect:" prefix. * <p>Not possible in {@code loadView}, since overridden * {@code loadView} versions in subclasses might rely on the * superclass always creating instances of the required view class. * @see #loadView * @see #requiredViewClass */ @Override protected View createView(String viewName, Locale locale) throws Exception { // If this resolver is not supposed to handle the given view, // return null to pass on to the next resolver in the chain. if (!canHandle(viewName, locale)) { return null; } // Check for special "redirect:" prefix. if (viewName.startsWith(REDIRECT_URL_PREFIX)) { String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length()); RedirectView view = new RedirectView(redirectUrl, isRedirectContextRelative(), isRedirectHttp10Compatible()); return applyLifecycleMethods(viewName, view); } // Check for special "forward:" prefix. if (viewName.startsWith(FORWARD_URL_PREFIX)) { String forwardUrl = viewName.substring(FORWARD_URL_PREFIX.length()); return new InternalResourceView(forwardUrl); } // Else fall back to superclass implementation: calling loadView. return super.createView(viewName, locale); }
@Override public View resolveViewName(String viewName, Locale locale) throws Exception { RequestAttributes attrs = RequestContextHolder.getRequestAttributes(); Assert.isInstanceOf(ServletRequestAttributes.class, attrs); List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest()); if (requestedMediaTypes != null) { List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes); View bestView = getBestView(candidateViews, requestedMediaTypes, attrs); if (bestView != null) { return bestView; } } if (this.useNotAcceptableStatusCode) { if (logger.isDebugEnabled()) { logger.debug("No acceptable view found; returning 406 (Not Acceptable) status code"); } return NOT_ACCEPTABLE_VIEW; } else { logger.debug("No acceptable view found; returning null"); return null; } }
private List<View> getCandidateViews(String viewName, Locale locale, List<MediaType> requestedMediaTypes) throws Exception { List<View> candidateViews = new ArrayList<View>(); for (ViewResolver viewResolver : this.viewResolvers) { View view = viewResolver.resolveViewName(viewName, locale); if (view != null) { candidateViews.add(view); } for (MediaType requestedMediaType : requestedMediaTypes) { List<String> extensions = this.contentNegotiationManager.resolveFileExtensions(requestedMediaType); for (String extension : extensions) { String viewNameWithExtension = viewName + "." + extension; view = viewResolver.resolveViewName(viewNameWithExtension, locale); if (view != null) { candidateViews.add(view); } } } } if (!CollectionUtils.isEmpty(this.defaultViews)) { candidateViews.addAll(this.defaultViews); } return candidateViews; }
@Override public View resolveViewName(String viewName, Locale locale) throws BeansException { ApplicationContext context = getApplicationContext(); if (!context.containsBean(viewName)) { if (logger.isDebugEnabled()) { logger.debug("No matching bean found for view name '" + viewName + "'"); } // Allow for ViewResolver chaining... return null; } if (!context.isTypeMatch(viewName, View.class)) { if (logger.isDebugEnabled()) { logger.debug("Found matching bean for view name '" + viewName + "' - to be ignored since it does not implement View"); } // Since we're looking into the general ApplicationContext here, // let's accept this as a non-match and allow for chaining as well... return null; } return context.getBean(viewName, View.class); }
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { return; } else if (returnValue instanceof View){ View view = (View) returnValue; mavContainer.setView(view); if (view instanceof SmartView) { if (((SmartView) view).isRedirectView()) { mavContainer.setRedirectModelScenario(true); } } } else { // should not happen throw new UnsupportedOperationException("Unexpected return type: " + returnType.getParameterType().getName() + " in method: " + returnType.getMethod()); } }
private ModelAndView getModelAndView(ModelAndViewContainer mavContainer, ModelFactory modelFactory, NativeWebRequest webRequest) throws Exception { modelFactory.updateModel(webRequest, mavContainer); if (mavContainer.isRequestHandled()) { return null; } ModelMap model = mavContainer.getModel(); ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model); if (!mavContainer.isViewReference()) { mav.setView((View) mavContainer.getView()); } if (model instanceof RedirectAttributes) { Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes(); HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes); } return mav; }
private void initContentNegotiatingViewResolver(View[] defaultViews) { // ContentNegotiatingResolver in the registry: elevate its precedence! this.order = (this.order == null ? Ordered.HIGHEST_PRECEDENCE : this.order); if (this.contentNegotiatingResolver != null) { if (!ObjectUtils.isEmpty(defaultViews)) { if (!CollectionUtils.isEmpty(this.contentNegotiatingResolver.getDefaultViews())) { List<View> views = new ArrayList<View>(this.contentNegotiatingResolver.getDefaultViews()); views.addAll(Arrays.asList(defaultViews)); this.contentNegotiatingResolver.setDefaultViews(views); } } } else { this.contentNegotiatingResolver = new ContentNegotiatingViewResolver(); this.contentNegotiatingResolver.setDefaultViews(Arrays.asList(defaultViews)); this.contentNegotiatingResolver.setViewResolvers(this.viewResolvers); this.contentNegotiatingResolver.setContentNegotiationManager(this.contentNegotiationManager); } }
@Test public void testBeanNameViewResolver() throws ServletException { StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(new MockServletContext()); MutablePropertyValues pvs1 = new MutablePropertyValues(); pvs1.addPropertyValue(new PropertyValue("url", "/example1.jsp")); wac.registerSingleton("example1", InternalResourceView.class, pvs1); MutablePropertyValues pvs2 = new MutablePropertyValues(); pvs2.addPropertyValue(new PropertyValue("url", "/example2.jsp")); wac.registerSingleton("example2", JstlView.class, pvs2); BeanNameViewResolver vr = new BeanNameViewResolver(); vr.setApplicationContext(wac); wac.refresh(); View view = vr.resolveViewName("example1", Locale.getDefault()); assertEquals("Correct view class", InternalResourceView.class, view.getClass()); assertEquals("Correct URL", "/example1.jsp", ((InternalResourceView) view).getUrl()); view = vr.resolveViewName("example2", Locale.getDefault()); assertEquals("Correct view class", JstlView.class, view.getClass()); assertEquals("Correct URL", "/example2.jsp", ((JstlView) view).getUrl()); }
private void doTestUrlBasedViewResolverWithPrefixes(UrlBasedViewResolver vr) throws Exception { StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(new MockServletContext()); wac.refresh(); vr.setPrefix("/WEB-INF/"); vr.setSuffix(".jsp"); vr.setApplicationContext(wac); View view = vr.resolveViewName("example1", Locale.getDefault()); assertEquals("Correct view class", JstlView.class, view.getClass()); assertEquals("Correct URL", "/WEB-INF/example1.jsp", ((InternalResourceView) view).getUrl()); view = vr.resolveViewName("example2", Locale.getDefault()); assertEquals("Correct view class", JstlView.class, view.getClass()); assertEquals("Correct URL", "/WEB-INF/example2.jsp", ((InternalResourceView) view).getUrl()); view = vr.resolveViewName("redirect:myUrl", Locale.getDefault()); assertEquals("Correct view class", RedirectView.class, view.getClass()); assertEquals("Correct URL", "myUrl", ((RedirectView) view).getUrl()); view = vr.resolveViewName("forward:myUrl", Locale.getDefault()); assertEquals("Correct view class", InternalResourceView.class, view.getClass()); assertEquals("Correct URL", "myUrl", ((InternalResourceView) view).getUrl()); }
@Test public void resolveViewNameWithPathExtension() throws Exception { request.setRequestURI("/test.xls"); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); View viewMock = mock(View.class, "application_xls"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null); given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn("application/vnd.ms-excel"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock, result); }
@Test public void resolveViewNameWithAcceptHeader() throws Exception { request.addHeader("Accept", "application/vnd.ms-excel"); Map<String, MediaType> mapping = Collections.singletonMap("xls", MediaType.valueOf("application/vnd.ms-excel")); MappingMediaTypeFileExtensionResolver extensionsResolver = new MappingMediaTypeFileExtensionResolver(mapping); ContentNegotiationManager manager = new ContentNegotiationManager(new HeaderContentNegotiationStrategy()); manager.addFileExtensionResolvers(extensionsResolver); viewResolver.setContentNegotiationManager(manager); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); View viewMock = mock(View.class, "application_xls"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null); given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn("application/vnd.ms-excel"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock, result); }
@Bean public ViewResolver viewResolver() { ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver(); List<View> defaultViews = new ArrayList<View>(); defaultViews.add(new MappingJackson2JsonView()); resolver.setDefaultViews(defaultViews); resolver.setOrder(0); List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>(); InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver(); internalResourceViewResolver.setPrefix("/WEB-INF/view/"); internalResourceViewResolver.setSuffix(".jsp"); internalResourceViewResolver.setOrder(1); viewResolvers.add(internalResourceViewResolver); resolver.setViewResolvers(viewResolvers); return resolver; }
@Test public void resolveViewContentTypeNull() throws Exception { request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); View viewMock = mock(View.class, "application_xml"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn(null); View result = viewResolver.resolveViewName(viewName, locale); assertNull("Invalid view", result); }
@Test public void resolveViewNoMatch() throws Exception { request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9"); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); View viewMock = mock(View.class, "application_xml"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn("application/pdf"); View result = viewResolver.resolveViewName(viewName, locale); assertNull("Invalid view", result); }
@Test public void resolveViewNoMatchUseUnacceptableStatus() throws Exception { viewResolver.setUseNotAcceptableStatusCode(true); request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9"); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); View viewMock = mock(View.class, "application_xml"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn("application/pdf"); View result = viewResolver.resolveViewName(viewName, locale); assertNotNull("Invalid view", result); MockHttpServletResponse response = new MockHttpServletResponse(); result.render(null, request, response); assertEquals("Invalid status code set", 406, response.getStatus()); }
@Test public void nestedViewResolverIsNotSpringBean() throws Exception { StaticWebApplicationContext webAppContext = new StaticWebApplicationContext(); webAppContext.setServletContext(new MockServletContext()); webAppContext.refresh(); InternalResourceViewResolver nestedResolver = new InternalResourceViewResolver(); nestedResolver.setApplicationContext(webAppContext); nestedResolver.setViewClass(InternalResourceView.class); viewResolver.setViewResolvers(new ArrayList<ViewResolver>(Arrays.asList(nestedResolver))); FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(MediaType.TEXT_HTML); viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy)); viewResolver.afterPropertiesSet(); String viewName = "view"; Locale locale = Locale.ENGLISH; View result = viewResolver.resolveViewName(viewName, locale); assertNotNull("Invalid view", result); }
@Override public ModelAndView resolveModelAndView(Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) { if (returnValue instanceof MySpecialArg) { return new ModelAndView(new View() { @Override public String getContentType() { return "text/html"; } @Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.getWriter().write("myValue"); } }); } return UNRESOLVED; }
@Override public View resolveViewName(final String viewName, Locale locale) throws Exception { return new AbstractView () { @Override public String getContentType() { return null; } @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { for (String key : attrsToValidate.keySet()) { assertTrue("Model should contain attribute named " + key, model.containsKey(key)); assertEquals(attrsToValidate.get(key), model.get(key)); validatedAttrCount++; } } }; }
@SuppressWarnings("unchecked") @Test public void resolveArgumentWithExistingPathVars() throws Exception { Map<String, String> uriTemplateVars = new HashMap<String, String>(); uriTemplateVars.put("name", "value"); request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars); Map<String, Object> pathVars; uriTemplateVars.put("oldName", "oldValue"); request.setAttribute(View.PATH_VARIABLES, uriTemplateVars); String result = (String) resolver.resolveArgument(paramNamedString, mavContainer, webRequest, null); assertEquals("PathVariable not resolved correctly", "value", result); pathVars = (Map<String, Object>) request.getAttribute(View.PATH_VARIABLES); assertNotNull(pathVars); assertEquals(2, pathVars.size()); assertEquals("value", pathVars.get("name")); assertEquals("oldValue", pathVars.get("oldName")); }
/** * Instantiates a new Success. * @param view the view */ @Autowired public Success(@Qualifier("cas2JstlSuccessView") final View view) { super(view); super.setSuccessResponse(true); }
@Test public void verifyOK() 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.setServerName(CAS_SERVER); mockRequest.setServerPort(CAS_PORT); mockRequest.setScheme(CAS_SCHEME); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); ((OAuth20WrapperController) oauth20WrapperController) .getServicesManager().save(getRegisteredService(REDIRECT_URI, SERVICE_NAME)); final Controller c = ((OAuth20WrapperController) oauth20WrapperController).getAuthorizeController(); ((OAuth20AuthorizeController) c).setLoginUrl(CAS_URL); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); final HttpSession session = mockRequest.getSession(); assertEquals(REDIRECT_URI, session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL)); assertEquals(SERVICE_NAME, session.getAttribute(OAuthConstants.OAUTH20_SERVICE_NAME)); final View view = modelAndView.getView(); assertTrue(view instanceof RedirectView); final RedirectView redirectView = (RedirectView) view; final MockHttpServletRequest reqSvc = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); reqSvc.setServerName(CAS_SERVER); reqSvc.setServerPort(CAS_PORT); reqSvc.setScheme(CAS_SCHEME); final URL url = new URL(OAuthUtils.addParameter(CAS_URL, "service", reqSvc.getRequestURL().toString())); final URL url2 = new URL(redirectView.getUrl()); assertEquals(url, url2); }
@Test public void verifyOKWithState() 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.STATE, STATE); mockRequest.setServerName(CAS_SERVER); mockRequest.setServerPort(CAS_PORT); mockRequest.setScheme(CAS_SCHEME); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); ((OAuth20WrapperController) oauth20WrapperController) .getServicesManager().save(getRegisteredService(REDIRECT_URI, SERVICE_NAME)); final Controller c = ((OAuth20WrapperController) oauth20WrapperController).getAuthorizeController(); ((OAuth20AuthorizeController) c).setLoginUrl(CAS_URL); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); final HttpSession session = mockRequest.getSession(); assertEquals(REDIRECT_URI, session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL)); assertEquals(SERVICE_NAME, session.getAttribute(OAuthConstants.OAUTH20_SERVICE_NAME)); assertEquals(STATE, session.getAttribute(OAuthConstants.OAUTH20_STATE)); final View view = modelAndView.getView(); assertTrue(view instanceof RedirectView); final RedirectView redirectView = (RedirectView) view; final MockHttpServletRequest reqSvc = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); reqSvc.setServerName(CAS_SERVER); reqSvc.setServerPort(CAS_PORT); reqSvc.setScheme(CAS_SCHEME); final URL url = new URL(OAuthUtils.addParameter(CAS_URL, "service", reqSvc.getRequestURL().toString())); final URL url2 = new URL(redirectView.getUrl()); assertEquals(url, url2); }
@Test public void verifyOK() throws Exception { 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.setServerName(CAS_SERVER); mockRequest.setServerPort(CAS_PORT); mockRequest.setScheme(CAS_SCHEME); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final ServicesManager servicesManager = mock(ServicesManager.class); final List<RegisteredService> services = new ArrayList<>(); services.add(getRegisteredService(REDIRECT_URI, SERVICE_NAME)); when(servicesManager.getAllServices()).thenReturn(services); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.setLoginUrl(CAS_URL); oauth20WrapperController.setServicesManager(servicesManager); oauth20WrapperController.afterPropertiesSet(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); final HttpSession session = mockRequest.getSession(); assertEquals(REDIRECT_URI, session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL)); assertEquals(SERVICE_NAME, session.getAttribute(OAuthConstants.OAUTH20_SERVICE_NAME)); final View view = modelAndView.getView(); assertTrue(view instanceof RedirectView); final RedirectView redirectView = (RedirectView) view; final MockHttpServletRequest reqSvc = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); reqSvc.setServerName(CAS_SERVER); reqSvc.setServerPort(CAS_PORT); reqSvc.setScheme(CAS_SCHEME); final URL url = new URL(OAuthUtils.addParameter(CAS_URL, "service", reqSvc.getRequestURL().toString())); final URL url2 = new URL(redirectView.getUrl()); assertEquals(url, url2); }
@Test public void verifyOKWithState() throws Exception { 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.STATE, STATE); mockRequest.setServerName(CAS_SERVER); mockRequest.setServerPort(CAS_PORT); mockRequest.setScheme(CAS_SCHEME); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final ServicesManager servicesManager = mock(ServicesManager.class); final List<RegisteredService> services = new ArrayList<>(); services.add(getRegisteredService(REDIRECT_URI, SERVICE_NAME)); when(servicesManager.getAllServices()).thenReturn(services); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.setLoginUrl(CAS_URL); oauth20WrapperController.setServicesManager(servicesManager); oauth20WrapperController.afterPropertiesSet(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); final HttpSession session = mockRequest.getSession(); assertEquals(REDIRECT_URI, session.getAttribute(OAuthConstants.OAUTH20_CALLBACKURL)); assertEquals(SERVICE_NAME, session.getAttribute(OAuthConstants.OAUTH20_SERVICE_NAME)); assertEquals(STATE, session.getAttribute(OAuthConstants.OAUTH20_STATE)); final View view = modelAndView.getView(); assertTrue(view instanceof RedirectView); final RedirectView redirectView = (RedirectView) view; final MockHttpServletRequest reqSvc = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); reqSvc.setServerName(CAS_SERVER); reqSvc.setServerPort(CAS_PORT); reqSvc.setScheme(CAS_SCHEME); final URL url = new URL(OAuthUtils.addParameter(CAS_URL, "service", reqSvc.getRequestURL().toString())); final URL url2 = new URL(redirectView.getUrl()); assertEquals(url, url2); }
@ConditionalOnMissingBean(name = "casSamlServiceSuccessView") @RefreshScope @Bean public View casSamlServiceSuccessView() { return new Saml10SuccessResponseView(protocolAttributeEncoder, servicesManager, casProperties.getAuthn().getMfa().getAuthenticationContextAttribute(), saml10ObjectBuilder(), new DefaultArgumentExtractor(new SamlServiceFactory()), StandardCharsets.UTF_8.name(), casProperties.getSamlCore().getSkewAllowance(), casProperties.getSamlCore().getIssuer(), casProperties.getSamlCore().getAttributeNamespace()); }
@ConditionalOnMissingBean(name = "casSamlServiceFailureView") @RefreshScope @Bean public View casSamlServiceFailureView() { return new Saml10FailureResponseView(protocolAttributeEncoder, servicesManager, casProperties.getAuthn().getMfa().getAuthenticationContextAttribute(), saml10ObjectBuilder(), new DefaultArgumentExtractor(new SamlServiceFactory()), StandardCharsets.UTF_8.name(), casProperties.getSamlCore().getSkewAllowance()); }
public Cas20ResponseView(final boolean successResponse, final ProtocolAttributeEncoder protocolAttributeEncoder, final ServicesManager servicesManager, final String authenticationContextAttribute, final View view) { super(successResponse, protocolAttributeEncoder, servicesManager, authenticationContextAttribute, view); }
public Cas30ResponseView(final boolean successResponse, final ProtocolAttributeEncoder protocolAttributeEncoder, final ServicesManager servicesManager, final String authenticationContextAttribute, final View view, final boolean releaseProtocolAttributes) { super(successResponse, protocolAttributeEncoder, servicesManager, authenticationContextAttribute, view); this.releaseProtocolAttributes = releaseProtocolAttributes; }
@Bean @ConditionalOnMissingBean(name = "cas2ServiceSuccessView") public View cas2ServiceSuccessView() { return new Cas20ResponseView(true, protocolAttributeEncoder, servicesManager, casProperties.getAuthn().getMfa().getAuthenticationContextAttribute(), this.cas2SuccessView); }
@Bean @ConditionalOnMissingBean(name = "cas3ServiceJsonView") public View cas3ServiceJsonView() { return new Cas30JsonResponseView(true, protocolAttributeEncoder, servicesManager, casProperties.getAuthn().getMfa().getAuthenticationContextAttribute(), casProperties.getAuthn().isReleaseProtocolAttributes()); }
@Bean @ConditionalOnMissingBean(name = "cas3ServiceSuccessView") public View cas3ServiceSuccessView() { final String authenticationContextAttribute = casProperties.getAuthn().getMfa().getAuthenticationContextAttribute(); final boolean isReleaseProtocolAttributes = casProperties.getAuthn().isReleaseProtocolAttributes(); return new Cas30ResponseView(true, protocolAttributeEncoder, servicesManager, authenticationContextAttribute, cas3SuccessView, isReleaseProtocolAttributes); }