@Test public void verifyResettingContexPath() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath(CONST_CONTEXT_PATH); final MockRequestContext context = new MockRequestContext(); context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse())); this.action.doExecute(context); assertEquals(CONST_CONTEXT_PATH + '/', this.warnCookieGenerator.getCookiePath()); assertEquals(CONST_CONTEXT_PATH + '/', this.tgtCookieGenerator.getCookiePath()); request.setContextPath(CONST_CONTEXT_PATH_2); this.action.doExecute(context); assertNotSame(CONST_CONTEXT_PATH_2 + '/', this.warnCookieGenerator.getCookiePath()); assertNotSame(CONST_CONTEXT_PATH_2 + '/', this.tgtCookieGenerator.getCookiePath()); assertEquals(CONST_CONTEXT_PATH + '/', this.warnCookieGenerator.getCookiePath()); assertEquals(CONST_CONTEXT_PATH + '/', this.tgtCookieGenerator.getCookiePath()); }
@Test public void verifySuccessfulAuthenticationWithServiceAndWarn() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); final MockRequestContext context = new MockRequestContext(); WebUtils.putLoginTicket(context, "LOGIN"); request.addParameter("lt", "LOGIN"); request.addParameter("username", "test"); request.addParameter("password", "test"); request.addParameter("warn", "true"); request.addParameter("service", "test"); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, response)); final Credential c = org.jasig.cas.authentication.TestUtils.getCredentialsWithSameUsernameAndPassword(); putCredentialInRequestScope(context, c); final MessageContext messageContext = mock(MessageContext.class); assertEquals("success", this.action.submit(context, c, messageContext).getId()); assertNotNull(response.getCookie(this.warnCookieGenerator.getCookieName())); }
@Test public void testFindRoles() throws Exception { RoleEntity dbResult = new RoleEntity() .setId("123") .setCode("12345") .setDescription("Description 12345"); Page<RoleEntity> pageResponseBody = new PageImpl<>(Arrays.asList(dbResult)); Page<RoleRestData> expectedResponseBody = new PageImpl<>(Arrays.asList(RoleRestData.builder() .fromRoleEntity(dbResult).build())); when(roleService.findRoles(anyString(), any())).thenReturn(pageResponseBody); ResultActions resultActions = mockMvc.perform(get("/api/roles") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("role-read-all")); MockHttpServletResponse response = resultActions .andReturn() .getResponse(); verify(roleService).findRoles(anyString(), any()); assertThat(response.getContentAsByteArray()).isEqualTo(objectMapper.writeValueAsBytes(expectedResponseBody)); }
@Test public void verifyWrongSecret() throws Exception { clearAllServices(); final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL); mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID); mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI); mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET); mockRequest.setParameter(OAuthConstants.CODE, CODE); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); ((OAuth20WrapperController) oauth20WrapperController) .getServicesManager().save(getRegisteredService(REDIRECT_URI, WRONG_CLIENT_SECRET)); oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(400, mockResponse.getStatus()); assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString()); }
@Test public void should_upload_and_delete_a_document() throws Exception { final MockHttpServletResponse response = mvc.perform(fileUpload("/documents") .file(FILE) .param("classification", Classifications.PRIVATE.toString()) .headers(headers)) .andReturn().getResponse(); final String url = getSelfUrlFromResponse(response); mvc.perform(delete(url) .headers(headers)) .andExpect(status().is(204)); mvc.perform(get(url) .headers(headers)) .andExpect(status().isNotFound()); }
@Test public void verifyValidServiceTicketAndFormatAsJson() throws Exception { final Service svc = CoreAuthenticationTestUtils.getService("proxyService"); final AuthenticationResult ctx = CoreAuthenticationTestUtils.getAuthenticationResult(getAuthenticationSystemSupport(), svc); final TicketGrantingTicket tId = getCentralAuthenticationService().createTicketGrantingTicket(ctx); final ServiceTicket sId = getCentralAuthenticationService().grantServiceTicket(tId.getId(), svc, ctx); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(SERVICE_PARAM, svc.getId()); request.addParameter(TICKET_PARAM, sId.getId()); request.addParameter("format", ValidationResponseType.JSON.name()); final ModelAndView modelAndView = this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse()); assertTrue(modelAndView.getView().toString().contains("Json")); }
@Test public void testDoFilterInternalWithInvalidOrgName() throws IOException, ServletException { JwtPayloadHelper payload = new JwtPayloadHelper() .withName("invalid-name") .withOrgType(ORG_TYPE); request.addHeader("Authorization", JwtTestHelper.createJwt(payload)); JwtAuthorizationFilter testJwtAuthFilter = new JwtAuthorizationFilter(authenticationManager); PowerMockito.mockStatic(SecurityContextHolder.class); SecurityContext mockSecurityContext = PowerMockito.mock(SecurityContext.class); PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(mockSecurityContext); testJwtAuthFilter.doFilterInternal(request, response, filterChain); verify(filterChain, times(1)).doFilter(any(MockHttpServletRequest.class), any(MockHttpServletResponse.class)); verify(SecurityContextHolder.getContext(), times(0)).setAuthentication(any(UsernamePasswordAuthenticationToken.class)); }
@Test public void verifyOK() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest( "GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET); final MockHttpSession mockSession = new MockHttpSession(); mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI); mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME); mockRequest.setSession(mockSession); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName()); final Map<String, Object> map = modelAndView.getModel(); assertEquals(SERVICE_NAME, map.get("serviceName")); assertEquals(REDIRECT_URI + '?' + OAuthConstants.CODE + '=' + SERVICE_TICKET, map.get("callbackUrl")); }
@Test public void testJWTFilter() throws Exception { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( "test-user", "test-password", Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) ); String jwt = tokenProvider.createToken(authentication, false); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt); request.setRequestURI("/api/test"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); jwtFilter.doFilter(request, response, filterChain); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user"); assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt); }
@Test public void testRenewWithServiceAndBadCredentials() throws Exception { final String ticketGrantingTicket = getCentralAuthenticationService() .createTicketGrantingTicket( TestUtils.getCredentialsWithSameUsernameAndPassword()); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockRequestContext context = new MockRequestContext(); context.getFlowScope().put("ticketGrantingTicketId", ticketGrantingTicket); request.addParameter("renew", "true"); request.addParameter("service", "test"); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, new MockHttpServletResponse())); context.getRequestScope().put("credentials", TestUtils.getCredentialsWithDifferentUsernameAndPassword()); context.getRequestScope().put( "org.springframework.validation.BindException.credentials", new BindException(TestUtils .getCredentialsWithDifferentUsernameAndPassword(), "credentials")); // this.action.bind(context); // assertEquals("error", this.action.submit(context).getId()); }
@Test public void verifyClientNoCasService() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.ACCESS_TOKEN_URL); mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID); mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI); mockRequest.setParameter(OAuth20Constants.CLIENT_SECRET, CLIENT_SECRET); mockRequest.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.name().toLowerCase()); final Principal principal = createPrincipal(); final RegisteredService registeredService = getRegisteredService(REDIRECT_URI, CLIENT_SECRET); final OAuthCode code = addCode(principal, registeredService); mockRequest.setParameter(OAuth20Constants.CODE, code.getId()); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null); oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse); assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus()); assertEquals(ERROR_EQUALS + OAuth20Constants.INVALID_REQUEST, mockResponse.getContentAsString()); }
@Test public void verifyClientNoClientSecret() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.ACCESS_TOKEN_URL); mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID); mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI); mockRequest.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.name().toLowerCase()); final Principal principal = createPrincipal(); final RegisteredService service = addRegisteredService(); final OAuthCode code = addCode(principal, service); mockRequest.setParameter(OAuth20Constants.CODE, code.getId()); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null); oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse); assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus()); assertEquals(ERROR_EQUALS + OAuth20Constants.INVALID_REQUEST, mockResponse.getContentAsString()); }
@Test public void verifyResettingContextPath() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath(CONST_CONTEXT_PATH); final MockRequestContext context = new MockRequestContext(); context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse())); this.action.doExecute(context); assertEquals(CONST_CONTEXT_PATH + '/', this.warnCookieGenerator.getCookiePath()); assertEquals(CONST_CONTEXT_PATH + '/', this.tgtCookieGenerator.getCookiePath()); request.setContextPath(CONST_CONTEXT_PATH_2); this.action.doExecute(context); assertNotSame(CONST_CONTEXT_PATH_2 + '/', this.warnCookieGenerator.getCookiePath()); assertNotSame(CONST_CONTEXT_PATH_2 + '/', this.tgtCookieGenerator.getCookiePath()); assertEquals(CONST_CONTEXT_PATH + '/', this.warnCookieGenerator.getCookiePath()); assertEquals(CONST_CONTEXT_PATH + '/', this.tgtCookieGenerator.getCookiePath()); }
@Test public void verifyValidServiceTicket() throws Exception { final AuthenticationContext ctx = org.jasig.cas.authentication.TestUtils .getAuthenticationContext(getAuthenticationSystemSupport(), SERVICE); final TicketGrantingTicket tId = getCentralAuthenticationService() .createTicketGrantingTicket(ctx); final ServiceTicket sId = getCentralAuthenticationService().grantServiceTicket(tId.getId(), SERVICE, ctx); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("service", SERVICE.getId()); request.addParameter("ticket", sId.getId()); assertEquals(AbstractServiceValidateController.DEFAULT_SERVICE_SUCCESS_VIEW_NAME, this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse()).getViewName()); }
@Test public void run_on_valid_response() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL); RequestContext context = RequestContext.getCurrentContext(); context.setRequest(request); MockHttpServletResponse response = new MockHttpServletResponse(); context.setResponseGZipped(false); context.setResponse(response); InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}", StandardCharsets.UTF_8); context.setResponseDataStream(in); filter.run(); assertEquals("UTF-8", response.getCharacterEncoding()); assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody()); }
@Test public void verifySsoSessionCookieOnServiceSsoDisallowed() throws Exception { final MockHttpServletResponse response = new MockHttpServletResponse(); final MockHttpServletRequest request = new MockHttpServletRequest(); final WebApplicationService svc = mock(WebApplicationService.class); when(svc.getId()).thenReturn("TestSsoFalse"); final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class); when(tgt.getId()).thenReturn(TEST_STRING); request.setCookies(new Cookie("TGT", "test5")); WebUtils.putTicketGrantingTicketInScopes(this.context, tgt); this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response)); this.context.getFlowScope().put("service", svc); final SendTicketGrantingTicketAction action = new SendTicketGrantingTicketAction(centralAuthenticationService, servicesManager, ticketGrantingTicketCookieGenerator, false); assertEquals(SUCCESS, action.execute(this.context).getId()); assertEquals(0, response.getCookies().length); }
@Test public void verifyTicketGrantingTicketNoTgt() throws Exception { final MockRequestContext context = new MockRequestContext(); context.getFlowScope().put("service", org.jasig.cas.services.TestUtils.getService()); final MockHttpServletRequest request = new MockHttpServletRequest(); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, new MockHttpServletResponse())); request.addParameter("service", "service"); final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class); when(tgt.getId()).thenReturn("bleh"); WebUtils.putTicketGrantingTicketInScopes(context, tgt); assertEquals("error", this.action.execute(context).getId()); }
@Test public void verifySuccessfulAuthenticationWithNoService() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockRequestContext context = new MockRequestContext(); WebUtils.putLoginTicket(context, "LOGIN"); request.addParameter("username", "test"); request.addParameter("password", "test"); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, new MockHttpServletResponse())); final Credential c = org.jasig.cas.authentication.TestUtils.getCredentialsWithSameUsernameAndPassword(); putCredentialInRequestScope(context, c); final MessageContext messageContext = mock(MessageContext.class); assertEquals("success", this.action.submit(context, c, messageContext).getId()); }
@Test public void onNonRepositoryRequestShouldPassTrough() throws Exception { MockFilterChain filterChain = new MockFilterChain(); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setMethod("GET"); request.setContextPath(""); request.setServletPath(null); request.setPathInfo(null); request.setRequestURI("/api/somethingDifferent/"); request.addHeader("Accept", "*/*"); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, filterChain); // no content set yet Assert.assertEquals(0, response.getContentLength()); }
@Test public void testSecurityProviderInstalled() { HttpRequestContextProvider provider = new HttpRequestContextProvider(); ServletModule module = new ServletModule(provider); CrnkBoot boot = new CrnkBoot(); boot.addModule(module); boot.boot(); SecurityProvider securityProvider = boot.getModuleRegistry().getSecurityProvider(); ServletContext servletContext = Mockito.mock(ServletContext.class); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); MockHttpServletResponse response = new MockHttpServletResponse(); request.addUserRole("guest"); request.addUserRole("admin"); provider.onRequestStarted(new HttpRequestContextBaseAdapter(new ServletRequestContext(servletContext, request, response, "api"))); Assert.assertFalse(securityProvider.isUserInRole("doesNotExist")); Assert.assertTrue(securityProvider.isUserInRole("guest")); Assert.assertTrue(securityProvider.isUserInRole("admin")); }
@Test public void verifyView() throws Exception { final ModelAndView modelAndView = this.getModelAndViewUponServiceValidationWithSecurePgtUrl(); final JstlView v = (JstlView) resolver.resolveViewName(modelAndView.getViewName(), Locale.getDefault()); final MockHttpServletRequest req = new MockHttpServletRequest(new MockServletContext()); v.setServletContext(req.getServletContext()); req.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, new GenericWebApplicationContext(req.getServletContext())); final Cas20ResponseView view = new Cas20ResponseView(v); final MockHttpServletResponse resp = new MockHttpServletResponse(); 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)); }
@Test public void onSimpleResourceGetShouldReturnOneResource() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setMethod("GET"); request.setContextPath(""); request.setServletPath("/api"); request.setPathInfo("/tasks/1"); request.setRequestURI("/api/tasks/1"); request.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE); request.addHeader("Accept", "*/*"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); String responseContent = response.getContentAsString(); log.debug("responseContent: {}", responseContent); assertNotNull(responseContent); assertJsonPartEquals("tasks", responseContent, "data.type"); assertJsonPartEquals("\"1\"", responseContent, "data.id"); assertJsonPartEquals(SOME_TASK_ATTRIBUTES, responseContent, "data.attributes"); assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data.links"); assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data.relationships.project.links"); }
@Test public void verifyValidServiceTicketAndBadFormat() throws Exception { final Service svc = org.jasig.cas.authentication.TestUtils.getService("proxyService"); final AuthenticationContext ctx = org.jasig.cas.authentication.TestUtils .getAuthenticationContext(getAuthenticationSystemSupport(), svc); final TicketGrantingTicket tId = getCentralAuthenticationService() .createTicketGrantingTicket(ctx); final ServiceTicket sId = getCentralAuthenticationService().grantServiceTicket(tId.getId(), svc, ctx); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("service", svc.getId()); request.addParameter("ticket", sId.getId()); request.addParameter("format", "NOTHING"); final ModelAndView modelAndView = this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse()); assertEquals(modelAndView.getViewName(), AbstractServiceValidateController.DEFAULT_SERVICE_FAILURE_VIEW_NAME); }
@Test public void verifyClientRedirectUriDoesNotStartWithServiceId() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.ACCESS_TOKEN_URL); mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID); mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, OTHER_REDIRECT_URI); mockRequest.setParameter(OAuth20Constants.CLIENT_SECRET, CLIENT_SECRET); mockRequest.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.name().toLowerCase()); final Principal principal = createPrincipal(); final RegisteredService service = addRegisteredService(); final OAuthCode code = addCode(principal, service); mockRequest.setParameter(OAuth20Constants.CODE, code.getId()); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null); oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse); assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus()); assertEquals(ERROR_EQUALS + OAuth20Constants.INVALID_REQUEST, mockResponse.getContentAsString()); }
@Test public void testAcceptPlainJson() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setMethod("GET"); request.setContextPath(""); request.setServletPath("/api"); request.setPathInfo("/tasks/1"); request.setRequestURI("/api/tasks/1"); request.addHeader("Accept", "application/json"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); String responseContent = response.getContentAsString(); log.debug("responseContent: {}", responseContent); assertNotNull(responseContent); assertJsonPartEquals("tasks", responseContent, "data.type"); assertJsonPartEquals("\"1\"", responseContent, "data.id"); assertJsonPartEquals(SOME_TASK_ATTRIBUTES, responseContent, "data.attributes"); assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data.links"); assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data.relationships.project.links"); }
@Test public void verifyValidServiceTicketWithInvalidPgt() throws Exception { final AuthenticationResult ctx = CoreAuthenticationTestUtils.getAuthenticationResult(getAuthenticationSystemSupport(), SERVICE); this.serviceValidateController.setProxyHandler(new Cas10ProxyHandler()); final TicketGrantingTicket tId = getCentralAuthenticationService().createTicketGrantingTicket(ctx); final ServiceTicket sId = getCentralAuthenticationService().grantServiceTicket(tId.getId(), SERVICE, ctx); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(SERVICE_PARAM, SERVICE.getId()); request.addParameter(TICKET_PARAM, sId.getId()); request.addParameter(PGT_URL_PARAM, "duh"); final ModelAndView modelAndView = this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse()); assertTrue(modelAndView.getView().toString().contains(SUCCESS)); assertNull(modelAndView.getModel().get(PGT_IOU_PARAM)); }
@Test public void testUpdateUserPassword() throws Exception { final UserEntity user = new UserEntity() .setId("user123"); when(userAdminService.updateUserPassword(eq("user123"), any())).thenReturn(user); ResultActions resultActions = mockMvc.perform(put("/api/users/user123/password") .content("{\"username\": \"user123\"}") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("user-update-password")); MockHttpServletResponse response = resultActions .andReturn() .getResponse(); assertThat(response.getContentAsByteArray()) .isEqualTo(objectMapper.writeValueAsBytes(UserRestData.builder().fromUserEntity(user).build())); verify(userAdminService).updateUserPassword(eq("user123"), any()); }
@Test public void ensureHostnameShouldDoSpnego() { final HostNameSpnegoKnownClientSystemsFilterAction action = new HostNameSpnegoKnownClientSystemsFilterAction("", "", 0, "\\w+\\.\\w+\\.\\w+"); final MockRequestContext ctx = new MockRequestContext(); final MockHttpServletRequest req = new MockHttpServletRequest(); req.setRemoteAddr(ALTERNATE_REMOTE_IP); final ServletExternalContext extCtx = new ServletExternalContext( new MockServletContext(), req, new MockHttpServletResponse()); ctx.setExternalContext(extCtx); final Event ev = action.doExecute(ctx); assertEquals(ev.getId(), new EventFactorySupport().yes(this).getId()); }
@Test public void verifyValidServiceTicketWithDifferentEncodingAndIgnoringCase() throws Exception { final String origSvc = "http://www.jasig.org?param=hello+world"; final Service svc = CoreAuthenticationTestUtils.getService(origSvc); final AuthenticationResult ctx = CoreAuthenticationTestUtils.getAuthenticationResult(getAuthenticationSystemSupport(), svc); this.serviceValidateController.setProxyHandler(new Cas10ProxyHandler()); final TicketGrantingTicket tId = getCentralAuthenticationService().createTicketGrantingTicket(ctx); final ServiceTicket sId = getCentralAuthenticationService().grantServiceTicket(tId.getId(), svc, ctx); final String reqSvc = "http://WWW.JASIG.ORG?PARAM=hello%20world"; final MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(SERVICE_PARAM, CoreAuthenticationTestUtils.getService(reqSvc).getId()); request.addParameter(TICKET_PARAM, sId.getId()); assertTrue(this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse()).getView().toString().contains(SUCCESS)); }
@Test public void verifyValidServiceTicketWithValidPgtAndProxyHandling() throws Exception { final AuthenticationContext ctx = org.jasig.cas.authentication.TestUtils .getAuthenticationContext(getAuthenticationSystemSupport(), SERVICE); final TicketGrantingTicket tId = getCentralAuthenticationService() .createTicketGrantingTicket(ctx); final ServiceTicket sId = getCentralAuthenticationService().grantServiceTicket(tId.getId(), SERVICE, ctx); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("service", SERVICE.getId()); request.addParameter("ticket", sId.getId()); request.addParameter("pgtUrl", "https://www.github.com"); final ModelAndView modelAndView = this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse()); assertEquals(AbstractServiceValidateController.DEFAULT_SERVICE_SUCCESS_VIEW_NAME, modelAndView.getViewName()); assertNotNull(modelAndView.getModel().get("pgtIou")); }
@Test public void ensureRemoteIpShouldNotBeChecked() { final BaseSpnegoKnownClientSystemsFilterAction action = new BaseSpnegoKnownClientSystemsFilterAction("^192\\.158\\..+"); final MockRequestContext ctx = new MockRequestContext(); final MockHttpServletRequest req = new MockHttpServletRequest(); req.setRemoteAddr("193.158.5.781"); final ServletExternalContext extCtx = new ServletExternalContext( new MockServletContext(), req, new MockHttpServletResponse()); ctx.setExternalContext(extCtx); final Event ev = action.doExecute(ctx); assertNotEquals(ev.getId(), new EventFactorySupport().yes(this).getId()); }
@Before public void setUp() throws Exception { applicationContext = ApplicationContextHelper.getApplicationContext(); ServiceRegistry registry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY); davHelper = (WebDAVHelper) applicationContext.getBean(WebDAVHelper.BEAN_NAME); auditRegistry = (AuditModelRegistryImpl) applicationContext.getBean(AUDIT_REGISTRY_BEAN_NAME); auditService = registry.getAuditService(); fileFolderService = registry.getFileFolderService(); transactionService = registry.getTransactionService(); testingMethod = new GetMethod(); mockResponse = new MockHttpServletResponse(); restartTransaction(TransactionActionEnum.ACTION_NONE); AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName()); companyHomeNodeRef = registry.getNodeLocatorService().getNode(CompanyHomeNodeLocator.NAME, null, null); rootTestFolder = fileFolderService.create(companyHomeNodeRef, ROOT_TEST_FOLDER_NAME, ContentModel.TYPE_FOLDER).getNodeRef(); }
@Test public void testUnacceptableRequestContentType() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setMethod("GET"); request.setContextPath(""); request.setServletPath("/api"); request.setPathInfo("/tasks"); request.setRequestURI("/api/tasks"); request.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE); request.addHeader("Accept", "application/xml"); request.addParameter("filter[Task][name]", "John"); request.setQueryString(URLEncoder.encode("filter[Task][name]", StandardCharsets.UTF_8.name()) + "=John"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); assertEquals(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, response.getStatus()); String responseContent = response.getContentAsString(); assertTrue(responseContent == null || "".equals(responseContent.trim())); }
@Test public void testSuccessfulServiceTicket() throws Exception { final MockRequestContext context = new MockRequestContext(); final MockHttpServletRequest request = new MockHttpServletRequest(); final Authentication authentication = TestUtils.getAuthentication("scootman28"); final TicketGrantingTicket t = new TicketGrantingTicketImpl("TGT-11", authentication, new NeverExpiresExpirationPolicy()); this.ticketRegistry.addTicket(t); request.setParameter("openid.identity", "http://openid.aol.com/scootman28"); request.setParameter("openid.return_to", "http://www.cnn.com"); final OpenIdService service = OpenIdService.createServiceFrom(request); context.getFlowScope().put("service", service); context.getFlowScope().put("ticketGrantingTicketId", t.getId()); context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse())); assertEquals("success", this.action.execute(context).getId()); }
@Test public void testFailedAuthenticationWithNoService() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockRequestContext context = new MockRequestContext(); request.addParameter("username", "test"); request.addParameter("password", "test2"); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, new MockHttpServletResponse())); context.getRequestScope().put("credentials", TestUtils.getCredentialsWithDifferentUsernameAndPassword()); context.getRequestScope().put( "org.springframework.validation.BindException.credentials", new BindException(TestUtils .getCredentialsWithDifferentUsernameAndPassword(), "credentials")); // this.action.bind(context); // assertEquals("error", this.action.submit(context).getId()); }
@Test public void verifyAddRegisteredServiceWithValues() throws Exception { final RegisteredServiceImpl svc = new RegisteredServiceImpl(); svc.setDescription("description"); svc.setServiceId("serviceId"); svc.setName("name"); svc.setEvaluationOrder(123); assertTrue(this.manager.getAllServices().isEmpty()); final RegisteredServiceEditBean.ServiceData data = registeredServiceFactory.createServiceData(svc); this.controller.saveService(new MockHttpServletRequest(), new MockHttpServletResponse(), data, mock(BindingResult.class)); final Collection<RegisteredService> services = this.manager.getAllServices(); assertEquals(1, services.size()); for(final RegisteredService rs : this.manager.getAllServices()) { assertTrue(rs instanceof RegexRegisteredService); } }
@Test public void verifyValidServiceTicketWithInvalidPgt() throws Exception { final AuthenticationContext ctx = org.jasig.cas.authentication.TestUtils .getAuthenticationContext(getAuthenticationSystemSupport(), SERVICE); this.serviceValidateController.setProxyHandler(new Cas10ProxyHandler()); final TicketGrantingTicket tId = getCentralAuthenticationService() .createTicketGrantingTicket(ctx); final ServiceTicket sId = getCentralAuthenticationService().grantServiceTicket(tId.getId(), SERVICE, ctx); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("service", SERVICE.getId()); request.addParameter("ticket", sId.getId()); request.addParameter("pgtUrl", "duh"); final ModelAndView modelAndView = this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse()); assertEquals(AbstractServiceValidateController.DEFAULT_SERVICE_SUCCESS_VIEW_NAME, modelAndView.getViewName()); assertNull(modelAndView.getModel().get("pgtIou")); }
@Test public void verifyDeleteService() throws Exception { final RegexRegisteredService r = new RegexRegisteredService(); r.setId(1200); r.setName(NAME); r.setServiceId("serviceId"); r.setEvaluationOrder(1); this.servicesManager.save(r); final MockHttpServletResponse response = new MockHttpServletResponse(); this.controller.manage(response); this.controller.deleteRegisteredService(1200, response); assertNull(this.servicesManager.findServiceBy(1200)); assertTrue(response.getContentAsString().contains("serviceName")); }