@Before public void setup() { this.request = new MockHttpServletRequest("GET", ""); this.request.setMethod("GET"); this.response = new MockHttpServletResponse(); this.chain = new MockFilterChain(); }
@Test public void printRequestWithEmptySessionMock() throws Exception { this.request.addParameter("param", "paramValue"); this.request.addHeader("header", "headerValue"); this.request.setCharacterEncoding("UTF-16"); String palindrome = "ablE was I ere I saw Elba"; byte[] bytes = palindrome.getBytes("UTF-16"); this.request.setContent(bytes); this.request.setSession(Mockito.mock(HttpSession.class)); this.handler.handle(this.mvcResult); HttpHeaders headers = new HttpHeaders(); headers.set("header", "headerValue"); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("param", "paramValue"); assertValue("MockHttpServletRequest", "HTTP Method", this.request.getMethod()); assertValue("MockHttpServletRequest", "Request URI", this.request.getRequestURI()); assertValue("MockHttpServletRequest", "Parameters", params); assertValue("MockHttpServletRequest", "Headers", headers); assertValue("MockHttpServletRequest", "Body", palindrome); }
request.setAsyncSupported(true); request.setMethod(this.method); request.setRequestURI(requestUri); request.setScheme(this.url.getScheme()); request.setServerName(this.url.getHost()); request.setServerPort(this.url.getPort()); request.setSecure(this.secure); request.setUserPrincipal(this.principal); request.setSession(this.session); request.setCharacterEncoding(this.characterEncoding); request.setContent(this.content); request.setContentType(this.contentType); request.addHeader(name, value); request.setQueryString(this.url.getRawQuery()); request.addParameter(name, value); String requestContentType = request.getContentType(); if (requestContentType != null) {
@Test public void getRequestURL() { request.setServerPort(8080); request.setRequestURI("/path"); assertEquals("http://localhost:8080/path", request.getRequestURL().toString()); request.setScheme("https"); request.setServerName("example.com"); request.setServerPort(8443); assertEquals("https://example.com:8443/path", request.getRequestURL().toString()); }
@Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { if (this.asRequestParameter) { request.setParameter("access_token", this.token); } else { request.addHeader("Authorization", "Bearer " + this.token); } return request; } }
@Test public void testDoFilterAuthenticateAll() throws Exception { AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class); AuthenticationManager manager = mock(AuthenticationManager.class); Authentication authentication = new TestingAuthenticationToken("un", "pwd", "ROLE_USER"); when(manager.authenticate(any(Authentication.class))).thenReturn(authentication); ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.setAuthenticateAllArtifacts(true); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("ticket", "ST-1-123"); request.setServletPath("/authenticate"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); .getContext().getAuthentication()).isNotNull().withFailMessage("Authentication should not be null"); verify(chain).doFilter(request, response); verifyZeroInteractions(successHandler); filter.setFilterProcessesUrl(request.getServletPath()); SecurityContextHolder.clearContext(); filter.doFilter(request, response, chain); verifyNoMoreInteractions(chain);
@Test public void filter_saves_when_needed() throws Exception { FilterChain chain = mock(FilterChain.class); request.setPathInfo("/login.do"); request.setRequestURI("/login.do"); request.setParameter(FORM_REDIRECT_PARAMETER, redirectUri); request.setServerName(new URL(redirectUri).getHost()); assertTrue(cache.shouldSaveFormRedirectParameter(request)); ServletResponse response = new MockHttpServletResponse(); spy.doFilter(request, response, chain); verify(spy, times(1)).shouldSaveFormRedirectParameter(request); verify(spy, times(1)).saveClientRedirect(any(), anyString()); Authentication auth = mock(Authentication.class); when(auth.isAuthenticated()).thenReturn(true); SecurityContextHolder.getContext().setAuthentication(auth); spy.doFilter(request, response, chain); verify(spy, times(2)).shouldSaveFormRedirectParameter(request); verify(spy, times(1)).saveClientRedirect(any(), anyString()); verify(chain, times(2)).doFilter(request, response); }
@Before public void setup() throws Exception { authentication = new UaaAuthentication( new UaaPrincipal("fake-id", "fake-username", "email@email.com", "origin", "", "uaa"), emptyList(), null ); authentication.setAuthenticationMethods(new HashSet<>()); mfaChecker = mock(MfaChecker.class); entryPoint = mock(AuthenticationEntryPoint.class); chain = mock(FilterChain.class); filter = new MfaRequiredFilter( mfaChecker, entryPoint ); when(mfaChecker.isMfaEnabled(any(IdentityZone.class), anyString())).thenReturn(true); request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); SecurityContextHolder.getContext().setAuthentication(authentication); }
@Test public void doFilterWhenNotAuthorizationRequestThenNextFilter() throws Exception { String requestUri = "/path"; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); request.setServletPath(requestUri); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); }
SecurityContext ctx = (SecurityContext) request.getSession(true) .getAttribute( HttpSessionSecurityContextRepository .SPRING_SECURITY_CONTEXT_KEY); assertNull(ctx); assertNull(SecurityContextHolder.getContext().getAuthentication()); clientDigestString(tmp, testUserName, testPassword, request.getMethod()); request.addHeader("Authorization", headerValue); (SecurityContext) request.getSession(true) .getAttribute( HttpSessionSecurityContextRepository .SPRING_SECURITY_CONTEXT_KEY); assertNotNull(ctx); Authentication auth = ctx.getAuthentication(); assertNotNull(auth); assertNull(SecurityContextHolder.getContext().getAuthentication()); checkForAuthenticatedRole(auth); assertEquals(testUserName, ((UserDetails) auth.getPrincipal()).getUsername()); assertTrue(auth.getAuthorities().contains(new GeoServerRole(rootRole))); assertTrue(auth.getAuthorities().contains(new GeoServerRole(derivedRole))); request.addHeader( "Authorization", "Basic "
@Test public void invalid_principal_throws() { Authentication a = mock(Authentication.class); when(a.getPrincipal()).thenReturn(new Object()); try { successHandler.setSavedAccountOptionCookie(new MockHttpServletRequest(), new MockHttpServletResponse(), a); }catch (IllegalArgumentException x) { assertEquals("Unrecognized authentication principle.", x.getMessage()); } }
@Test public void testWidgetDeactivated() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/stagemonitor/spans"); request.addParameter("connectionId", ""); MockHttpServletResponse response = new MockHttpServletResponse(); Mockito.when(servletPlugin.isWidgetAndStagemonitorEndpointsAllowed(eq(request))).thenReturn(Boolean.FALSE); ConfigurationRegistry configuration = mock(ConfigurationRegistry.class); when(configuration.getConfig(ServletPlugin.class)).thenReturn(servletPlugin); new MockFilterChain(spanServlet, new StagemonitorSecurityFilter(configuration)).doFilter(request, response); Assert.assertEquals(404, response.getStatus()); } }
@Test public void authenticatesValidUser() throws Exception { String msg = "{ \"username\":\"marissa\", \"password\":\"koala\"}"; AuthenticationManager am = mock(AuthenticationManager.class); Authentication result = mock(Authentication.class); when(am.authenticate(any(AuthzAuthenticationRequest.class))).thenReturn(result); AuthzAuthenticationFilter filter = new AuthzAuthenticationFilter(am); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/oauth/authorize"); request.setParameter("credentials", msg); MockHttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(request, response, new MockFilterChain()); }
@Test public void testDoNotTrackDisabled() throws Exception { when(servletPlugin.isHonorDoNotTrackHeader()).thenReturn(true); final MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("dnt", "0"); Scope activeScope = new MonitoredHttpRequest(request, mock(StatusExposingByteCountingServletResponse.class), mock(FilterChain.class), configuration, mock(ExecutorService.class)).createScope(); SpanWrapper span = SpanContextInformation.getCurrent().getSpanWrapper(); assertThat(span.getNumberTag(Tags.SAMPLING_PRIORITY.getKey())).isNotEqualTo(0); activeScope.close(); }
@Test public void getWhenUsingCustomHttpFirewallThenFirewallIsInvoked() throws Exception { this.spring.configLocations(xml("HttpFirewall")).autowire(); FirewalledRequest request = new FirewalledRequest(new MockHttpServletRequest()) { @Override public void reset() { } }; HttpServletResponse response = new MockHttpServletResponse(); HttpFirewall firewall = this.spring.getContext().getBean(HttpFirewall.class); when(firewall.getFirewalledRequest(any(HttpServletRequest.class))).thenReturn(request); when(firewall.getFirewalledResponse(any(HttpServletResponse.class))).thenReturn(response); this.mvc.perform(get("/unprotected")); verify(firewall).getFirewalledRequest(any(HttpServletRequest.class)); verify(firewall).getFirewalledResponse(any(HttpServletResponse.class)); }
@Test public void doFilterWhenAuthorizationFailsThenHandleOAuth2AuthorizationException() throws Exception { String requestUri = "/callback/client-1"; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); request.setServletPath(requestUri); request.addParameter(OAuth2ParameterNames.CODE, "code"); request.addParameter(OAuth2ParameterNames.STATE, "state"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.setUpAuthorizationRequest(request, response, this.registration1); OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT); when(this.authenticationManager.authenticate(any(Authentication.class))) .thenThrow(new OAuth2AuthorizationException(error)); this.filter.doFilter(request, response, filterChain); assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/callback/client-1?error=invalid_grant"); }
@Test public void doFilterWhenAuthorizationResponseSuccessAndAnonymousAccessNullAuthenticationThenAuthorizedClientSavedToHttpSession() throws Exception { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); SecurityContextHolder.setContext(securityContext); // null Authentication String requestUri = "/callback/client-1"; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); request.setServletPath(requestUri); request.addParameter(OAuth2ParameterNames.CODE, "code"); request.addParameter(OAuth2ParameterNames.STATE, "state"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.setUpAuthorizationRequest(request, response, this.registration1); this.setUpAuthenticationResult(this.registration1); this.filter.doFilter(request, response, filterChain); OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository.loadAuthorizedClient( this.registration1.getRegistrationId(), null, request); assertThat(authorizedClient).isNotNull(); assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1); assertThat(authorizedClient.getPrincipalName()).isEqualTo("anonymousUser"); assertThat(authorizedClient.getAccessToken()).isNotNull(); HttpSession session = request.getSession(false); assertThat(session).isNotNull(); @SuppressWarnings("unchecked") Map<String, OAuth2AuthorizedClient> authorizedClients = (Map<String, OAuth2AuthorizedClient>) session.getAttribute(HttpSessionOAuth2AuthorizedClientRepository.class.getName() + ".AUTHORIZED_CLIENTS"); assertThat(authorizedClients).isNotEmpty(); assertThat(authorizedClients).hasSize(1); assertThat(authorizedClients.values().iterator().next()).isSameAs(authorizedClient); }
@Test public void unapprovedFormRedirectRequestDoesNotSave() throws IOException, ServletException { request.setPathInfo("/login.do"); request.setRequestURI("/login.do"); request.setMethod(HttpMethod.POST.name()); request.setParameter(FORM_REDIRECT_PARAMETER, "http://test.com"); request.setServerName("not-test.com"); spy.doFilter(request, new MockHttpServletResponse(), mock(FilterChain.class)); verify(spy, never()).saveClientRedirect(any(HttpServletRequest.class), anyString()); } }
@Test(expected = OpenIDConsumerException.class) public void discoveryExceptionRaisesOpenIDException() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); when(mgr.discover(any())).thenThrow(new DiscoveryException("msg")); consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); }
modifyChain(pattern, false, true, null); SecurityContextHolder.getContext().setAuthentication(null); response = new MockHttpServletResponse(); chain = new MockFilterChain(); request.setQueryString(authKeyUrlParam + "=" + authKey); request.addParameter(authKeyUrlParam, authKey); request.getSession(false) .getAttribute( HttpSessionSecurityContextRepository .SPRING_SECURITY_CONTEXT_KEY); assertNotNull(ctx); Authentication auth = ctx.getAuthentication(); assertNotNull(auth); assertNull(SecurityContextHolder.getContext().getAuthentication()); checkForAuthenticatedRole(auth); assertEquals(testUserName, auth.getPrincipal()); chain = new MockFilterChain(); request.setQueryString(authKeyUrlParam + "=abc"); request.addParameter(authKeyUrlParam, "abc"); request.setQueryString(authKeyUrlParam + "=" + authKey); request.addParameter(authKeyUrlParam, authKey); getProxy().doFilter(request, response, chain);