@Test public void testAddEventWithWebAuthenticationDetails() { HttpSession session = new MockHttpSession(null, "test-session-id"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); request.setRemoteAddr("1.2.3.4"); WebAuthenticationDetails details = new WebAuthenticationDetails(request); Map<String, Object> data = new HashMap<>(); data.put("test-key", details); AuditEvent event = new AuditEvent("test-user", "test-type", data); customAuditEventRepository.add(event); List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).hasSize(1); PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0); assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4"); assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id"); }
@Test public void testNoCasService() throws Exception { 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(); final ServicesManager servicesManager = mock(ServicesManager.class); when(servicesManager.getAllServices()).thenReturn(new ArrayList<RegisteredService>()); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.setServicesManager(servicesManager); oauth20WrapperController.afterPropertiesSet(); oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(400, mockResponse.getStatus()); assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString()); }
@Test public void verifyNoCasService() 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.handleRequest(mockRequest, mockResponse); assertEquals(400, mockResponse.getStatus()); assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString()); }
public void test_for_issue() throws Exception { MockHttpServletRequest mockReq = new MockHttpServletRequest(); DefaultSavedRequest request = new DefaultSavedRequest(mockReq, new PortResolver() { public int getServerPort(ServletRequest servletRequest) { return 0; } }); String str = JSON.toJSONString(request, SerializerFeature.WriteClassName); // System.out.println(str); JSON.parseObject(str, Object.class, config); JSON.parseObject(str); }
private Map<?, ?> renderView() 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 Cas30ResponseView view = new Cas30ResponseView(v); view.setServicesManager(this.servicesManager); view.setCasAttributeEncoder(new DefaultCasAttributeEncoder(this.servicesManager)); final MockHttpServletResponse resp = new MockHttpServletResponse(); view.render(modelAndView.getModel(), req, resp); return (Map<?, ?>) req.getAttribute(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES); }
@Test public void verifySuccessfulAuthenticationWithServiceAndWarn() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); final MockRequestContext context = new MockRequestContext(); request.addParameter(USERNAME_PARAM, TEST); request.addParameter(PASSWORD_PARAM, TEST); request.addParameter("warn", "true"); request.addParameter(CasProtocolConstants.PARAMETER_SERVICE, TEST); context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response)); final Credential c = CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(); putCredentialInRequestScope(context, c); assertEquals(CasWebflowConstants.TRANSITION_ID_SUCCESS, this.action.execute(context).getId()); assertNotNull(response.getCookie(this.warnCookieGenerator.getCookieName())); }
@Test public void ensureHostnameAndIpShouldDoSpnego() { final HostNameSpnegoKnownClientSystemsFilterAction action = new HostNameSpnegoKnownClientSystemsFilterAction("74\\..+", "", 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 ensureRemoteIpShouldBeChecked() { final BaseSpnegoKnownClientSystemsFilterAction action = new BaseSpnegoKnownClientSystemsFilterAction("^192\\.158\\..+"); final MockRequestContext ctx = new MockRequestContext(); final MockHttpServletRequest req = new MockHttpServletRequest(); req.setRemoteAddr("192.158.5.781"); 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 testRenewWithServiceAndSameCredentials() 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"); request.addParameter("username", "test"); request.addParameter("password", "test"); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, new MockHttpServletResponse())); context.getFlowScope().put("service", TestUtils.getService("test")); // this.action.bind(context); // assertEquals("warn", this.action.submit(context).getId()); }
@Test public void verifyValidServiceTicketAndPgtUrlMismatch() 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(PGT_URL_PARAM, "http://www.github.com"); final ModelAndView modelAndView = this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse()); assertFalse(modelAndView.getView().toString().contains(SUCCESS)); assertNull(modelAndView.getModel().get(PGT_IOU_PARAM)); }
@Test public void testSuccessfulAuthenticationWithNoServiceAndWarn() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); final MockRequestContext context = new MockRequestContext(); request.addParameter("username", "test"); request.addParameter("password", "test"); request.addParameter("warn", "true"); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, response)); context.getRequestScope().put("credentials", TestUtils.getCredentialsWithSameUsernameAndPassword()); // this.action.bind(context); // assertEquals("success", this.action.submit(context).getId()); // assertNotNull(response.getCookie(this.warnCookieGenerator // .getCookieName())); }
@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 testRenewWithServiceAndDifferentCredentials() 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"); request.addParameter("username", "test2"); request.addParameter("password", "test2"); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, new MockHttpServletResponse())); // this.action.bind(context); // assertEquals("success", 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 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 verifySuccessfulServiceTicket() throws Exception { final MockRequestContext context = new MockRequestContext(); final MockHttpServletRequest request = new MockHttpServletRequest(); final Authentication authentication = org.jasig.cas.authentication.TestUtils.getAuthentication("scootman28"); final TicketGrantingTicket t = new TicketGrantingTicketImpl("TGT-11", authentication, new NeverExpiresExpirationPolicy()); this.ticketRegistry.addTicket(t); request.setParameter(OpenIdProtocolConstants.OPENID_IDENTITY, "http://openid.aol.com/scootman28"); request.setParameter(OpenIdProtocolConstants.OPENID_RETURNTO, "http://www.cnn.com"); final OpenIdService service = new OpenIdServiceFactory().createService(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()); }
/** * ?zone={zone_id}&pub={publisher_id}&prot={protocol}&h={height}&w={width}&sd={startdelay}&mime={mime_type}&domain={domain}&page={page}&ad={adid} */ @Test public void testParamsComplete() { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); request.addParameter("site", "1"); RequestSessionAgent agent = null; try { agent = new RequestSessionAgent(request, response); } catch (final RequestException e) { Assert.fail(e.getMessage()); } Assert.assertEquals("1", agent.getParamValues().getSite().getId()); }
@Test public void verifyClientNoAuthorizationCode() 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); 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 verifyInvalidServiceTicket() 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); getCentralAuthenticationService().destroyTicketGrantingTicket(tId.getId()); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("service", SERVICE.getId()); request.addParameter("ticket", sId.getId()); assertEquals(AbstractServiceValidateController.DEFAULT_SERVICE_FAILURE_VIEW_NAME, this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse()).getViewName()); }
public GoogleAccountsService getGoogleAccountsService() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); final String samlRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<samlp:AuthnRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" " + "ID=\"5545454455\" Version=\"2.0\" IssueInstant=\"Value\" " + "ProtocolBinding=\"urn:oasis:names.tc:SAML:2.0:bindings:HTTP-Redirect\" " + "ProviderName=\"https://localhost:8443/myRutgers\" AssertionConsumerServiceURL=\"https://localhost:8443/myRutgers\"/>"; request.setParameter(SamlProtocolConstants.PARAMETER_SAML_REQUEST, encodeMessage(samlRequest)); request.setParameter(SamlProtocolConstants.PARAMETER_SAML_RELAY_STATE, "RelayStateAddedHere"); final RegisteredService regSvc = mock(RegisteredService.class); when(regSvc.getUsernameAttributeProvider()).thenReturn(new DefaultRegisteredServiceUsernameProvider()); final ServicesManager servicesManager = mock(ServicesManager.class); when(servicesManager.findServiceBy(any(Service.class))).thenReturn(regSvc); return factory.createService(request); }
@Test public void verifySuccessfulAuthenticationWithNoServiceAndWarn() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); final MockRequestContext context = new MockRequestContext(); request.addParameter(USERNAME_PARAM, TEST); request.addParameter(PASSWORD_PARAM, TEST); request.addParameter("warn", "true"); context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response)); final Credential c = CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(); putCredentialInRequestScope(context, c); assertEquals(CasWebflowConstants.TRANSITION_ID_SUCCESS, this.action.execute(context).getId()); assertNotNull(WebUtils.getTicketGrantingTicketId(context)); assertNotNull(response.getCookie(this.warnCookieGenerator.getCookieName())); }
@Test public void testOK() 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 OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.afterPropertiesSet(); 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 verifyOKWithState() 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); mockSession.putValue(OAuthConstants.OAUTH20_STATE, STATE); 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 + '&' + OAuthConstants.STATE + '=' + STATE, map.get("callbackUrl")); }
@Test public void verifyRenewWithServiceAndDifferentCredentials() throws Exception { final Credential c = org.jasig.cas.authentication.TestUtils.getCredentialsWithSameUsernameAndPassword(); final AuthenticationContext ctx = org.jasig.cas.authentication.TestUtils.getAuthenticationContext( getAuthenticationSystemSupport(), TestUtils.getService("test"), c); final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(ctx); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockRequestContext context = new MockRequestContext(); WebUtils.putLoginTicket(context, "LOGIN"); WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket); request.addParameter("renew", "true"); request.addParameter("service", TestUtils.getService("test").getId()); request.addParameter("username", "test2"); request.addParameter("password", "test2"); context.setExternalContext(new ServletExternalContext( new MockServletContext(), request, new MockHttpServletResponse())); final MessageContext messageContext = mock(MessageContext.class); assertEquals("success", this.action.submit(context, c, messageContext).getId()); }
@Test public void verifyRedirectUriDoesNotStartWithServiceId() 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(OTHER_REDIRECT_URI, CLIENT_SECRET)); oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(400, mockResponse.getStatus()); assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString()); }
@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()); }
@Before public void onSetUp() throws Exception { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.requestContext = mock(RequestContext.class); final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class); when(this.requestContext.getExternalContext()).thenReturn(servletExternalContext); when(servletExternalContext.getNativeRequest()).thenReturn(request); when(servletExternalContext.getNativeResponse()).thenReturn(response); final LocalAttributeMap flowScope = new LocalAttributeMap(); when(this.requestContext.getFlowScope()).thenReturn(flowScope); this.warnCookieGenerator = new CookieRetrievingCookieGenerator(); this.serviceRegistryDao = new InMemoryServiceRegistryDaoImpl(); this.serviceManager = new DefaultServicesManagerImpl(serviceRegistryDao); this.serviceManager.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); this.serviceManager.reload(); this.warnCookieGenerator.setCookieName("test"); this.ticketGrantingTicketCookieGenerator = new CookieRetrievingCookieGenerator(); this.ticketGrantingTicketCookieGenerator.setCookieName(COOKIE_TGC_ID); this.logoutAction = new LogoutAction(); this.logoutAction.setServicesManager(this.serviceManager); }
@Test public void verifyInvalidServiceTicket() throws Exception { final AuthenticationResult ctx = CoreAuthenticationTestUtils .getAuthenticationResult(getAuthenticationSystemSupport(), SERVICE); final TicketGrantingTicket tId = getCentralAuthenticationService().createTicketGrantingTicket(ctx); final ServiceTicket sId = getCentralAuthenticationService().grantServiceTicket(tId.getId(), SERVICE, ctx); getCentralAuthenticationService().destroyTicketGrantingTicket(tId.getId()); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(SERVICE_PARAM, SERVICE.getId()); request.addParameter(TICKET_PARAM, sId.getId()); assertFalse(this.serviceValidateController.handleRequestInternal(request, new MockHttpServletResponse()).getView().toString().contains(SUCCESS)); }
/** * Executes WebDAV method for testing * <p> * Sets content to request from a test file * * @param methodName Method to prepare, should be initialized (PUT, LOCK, UNLOCK are supported) * @param fileName the name of the file set to the context, can be used with path, i.e. "path/to/file/fileName.txt" * @param content If <b>not null</b> adds test content to the request * @param headers to set to request, can be null * @throws Exception */ private void executeMethod(String methodName, String fileName, byte[] content, Map<String, String> headers) throws Exception { if (methodName == WebDAV.METHOD_PUT) method = new PutMethod(); else if (methodName == WebDAV.METHOD_LOCK) method = new LockMethod(); else if (methodName == WebDAV.METHOD_UNLOCK) method = new UnlockMethod(); if (method != null) { request = new MockHttpServletRequest(methodName, "/alfresco/webdav/" + fileName); response = new MockHttpServletResponse(); request.setServerPort(8080); request.setServletPath("/webdav"); if (content != null) { request.setContent(content); } if (headers != null && !headers.isEmpty()) { for (String key : headers.keySet()) { request.addHeader(key, headers.get(key)); } } method.setDetails(request, response, webDAVHelper, companyHomeNodeRef); method.execute(); } }
@Test public void verifyNoExistingAccessToken() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.PROFILE_URL); mockRequest.setParameter(OAuth20Constants.ACCESS_TOKEN, "DOES NOT EXIST"); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final ResponseEntity<String> entity = oAuth20ProfileController.handleRequest(mockRequest, mockResponse); assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode()); assertEquals(CONTENT_TYPE, mockResponse.getContentType()); assertTrue(entity.getBody().contains(OAuth20Constants.EXPIRED_ACCESS_TOKEN)); }
@Test public void shouldFilter_on_default_swagger_url() { MockHttpServletRequest request = new MockHttpServletRequest("GET", DEFAULT_URL); RequestContext.getCurrentContext().setRequest(request); assertTrue(filter.shouldFilter()); }
@Test public void testResponseWithNoAttributes() throws Exception { final Map<String, Object> model = new HashMap<String, Object>(); final SimplePrincipal principal = new SimplePrincipal("testPrincipal"); final Map<String, Object> authAttributes = new HashMap<String, Object>(); authAttributes.put( SamlAuthenticationMetaDataPopulator.ATTRIBUTE_AUTHENTICATION_METHOD, SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT); authAttributes.put("testSamlAttribute", "value"); final Authentication primary = TestUtils.getAuthentication(principal, authAttributes); final Assertion assertion = new ImmutableAssertion( primary, Collections.singletonList(primary), TestUtils.getService(), true); model.put("assertion", assertion); final MockHttpServletResponse servletResponse = new MockHttpServletResponse(); this.response.renderMergedOutputModel(model, new MockHttpServletRequest(), servletResponse); final String written = servletResponse.getContentAsString(); assertTrue(written.contains("testPrincipal")); assertTrue(written.contains(SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT)); assertTrue(written.contains("AuthenticationMethod")); }
@Test public void verifyNoCode() throws Exception { 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); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.afterPropertiesSet(); oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(400, mockResponse.getStatus()); assertEquals("error=" + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString()); }
@Test public void testJWTFilterInvalidToken() throws Exception { String jwt = "wrong_jwt"; 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()).isNull(); }
@Test public void verifyNoCasService() throws Exception { clearAllServices(); final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.AUTHORIZE_URL); mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID); mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final ModelAndView modelAndView = oAuth20AuthorizeEndpointController.handleRequest(mockRequest, mockResponse); assertEquals(OAuth20Constants.ERROR_VIEW, modelAndView.getViewName()); }
protected final ModelAndView getModelAndViewUponServiceValidationWithSecurePgtUrl() throws Exception { final TicketGrantingTicket tId = getCentralAuthenticationService() .createTicketGrantingTicket(TestUtils.getCredentialsWithSameUsernameAndPassword()); final ServiceTicket sId = getCentralAuthenticationService().grantServiceTicket(tId.getId(), TestUtils.getService()); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("service", TestUtils.getService().getId()); request.addParameter("ticket", sId.getId()); request.addParameter("pgtUrl", "https://www.github.com"); return this.serviceValidateController .handleRequestInternal(request, new MockHttpServletResponse()); }
@Test public void testCustomSpEntityIdForPostBinding() throws Exception { final SAML2Client client = getClient(); client.getConfiguration().setServiceProviderEntityId("http://localhost:8080/callback"); final WebContext context = new J2EContext(new MockHttpServletRequest(), new MockHttpServletResponse()); final RedirectAction action = client.getRedirectAction(context); assertTrue(getDecodedAuthnRequest(action.getContent()) .contains( "<saml2:Issuer xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\">http://localhost:8080/callback</saml2:Issuer>")); }
@Test public void testResponse() { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("TARGET", "service"); final SamlService impl = SamlService.createServiceFrom(request); final Response response = impl.getResponse("ticketId"); assertNotNull(response); assertEquals(ResponseType.REDIRECT, response.getResponseType()); assertTrue(response.getUrl().contains("SAMLart=")); }
@Test public void shouldNotFilter_on_wrong_url() { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/management/info"); RequestContext.getCurrentContext().setRequest(request); assertFalse(filter.shouldFilter()); }
@Test public void verifyServiceCreationNoService() { final MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(CasProtocolConstants.PARAMETER_TICKET, "ticket"); final WebApplicationServiceFactory factory = new WebApplicationServiceFactory(); final WebApplicationService service = factory.createService(request); assertNull(service); }