Convert to assertj
Fixes gh-3175
This commit is contained in:
@@ -16,34 +16,36 @@
|
||||
package org.springframework.security.web;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.security.web.PortMapperImpl;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Tests {@link PortMapperImpl}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class PortMapperImplTests extends TestCase {
|
||||
public class PortMapperImplTests {
|
||||
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void testDefaultMappingsAreKnown() throws Exception {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
assertThat(portMapper.lookupHttpPort(Integer.valueOf(443))).isEqualTo(Integer.valueOf(80));
|
||||
assertEquals(Integer.valueOf(8080),
|
||||
assertThat(portMapper.lookupHttpPort(Integer.valueOf(443))).isEqualTo(
|
||||
Integer.valueOf(80));
|
||||
assertThat(Integer.valueOf(8080)).isEqualTo(
|
||||
portMapper.lookupHttpPort(Integer.valueOf(8443)));
|
||||
assertEquals(Integer.valueOf(443),
|
||||
assertThat(Integer.valueOf(443)).isEqualTo(
|
||||
portMapper.lookupHttpsPort(Integer.valueOf(80)));
|
||||
assertEquals(Integer.valueOf(8443),
|
||||
assertThat(Integer.valueOf(8443)).isEqualTo(
|
||||
portMapper.lookupHttpsPort(Integer.valueOf(8080)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectsEmptyMap() throws Exception {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
|
||||
@@ -56,6 +58,7 @@ public class PortMapperImplTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectsNullMap() throws Exception {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
|
||||
@@ -68,11 +71,13 @@ public class PortMapperImplTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetTranslatedPortMappings() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
assertThat(portMapper.getTranslatedPortMappings()).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRejectsOutOfRangeMappings() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
@@ -87,11 +92,13 @@ public class PortMapperImplTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReturnsNullIfHttpPortCannotBeFound() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
assertThat(portMapper.lookupHttpPort(Integer.valueOf("34343")) == null).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSupportsCustomMappings() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
@@ -99,8 +106,9 @@ public class PortMapperImplTests extends TestCase {
|
||||
|
||||
portMapper.setPortMappings(map);
|
||||
|
||||
assertThat(portMapper.lookupHttpPort(Integer.valueOf(442))).isEqualTo(Integer.valueOf(79));
|
||||
assertEquals(Integer.valueOf(442),
|
||||
assertThat(portMapper.lookupHttpPort(Integer.valueOf(442))).isEqualTo(
|
||||
Integer.valueOf(79));
|
||||
assertThat(Integer.valueOf(442)).isEqualTo(
|
||||
portMapper.lookupHttpsPort(Integer.valueOf(79)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,19 +16,17 @@
|
||||
package org.springframework.security.web;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.security.web.PortMapperImpl;
|
||||
import org.springframework.security.web.PortResolverImpl;
|
||||
|
||||
/**
|
||||
* Tests {@link PortResolverImpl}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class PortResolverImplTests extends TestCase {
|
||||
public class PortResolverImplTests {
|
||||
// ~ Constructors
|
||||
// ===================================================================================================
|
||||
|
||||
@@ -36,17 +34,9 @@ public class PortResolverImplTests extends TestCase {
|
||||
super();
|
||||
}
|
||||
|
||||
public PortResolverImplTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectsBuggyIeHttpRequest() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
|
||||
@@ -56,6 +46,7 @@ public class PortResolverImplTests extends TestCase {
|
||||
assertThat(pr.getServerPort(request)).isEqualTo(8080);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectsBuggyIeHttpsRequest() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
|
||||
@@ -65,6 +56,7 @@ public class PortResolverImplTests extends TestCase {
|
||||
assertThat(pr.getServerPort(request)).isEqualTo(8443);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectsEmptyPortMapper() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
|
||||
@@ -77,6 +69,7 @@ public class PortResolverImplTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
assertThat(pr.getPortMapper() != null).isTrue();
|
||||
@@ -84,6 +77,7 @@ public class PortResolverImplTests extends TestCase {
|
||||
assertThat(pr.getPortMapper() != null).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
package org.springframework.security.web.access.channel;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
@@ -26,8 +27,7 @@ import java.util.Vector;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.access.ConfigAttribute;
|
||||
@@ -42,10 +42,10 @@ import org.springframework.security.web.access.channel.ChannelProcessor;
|
||||
* @author Ben Alex
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public class ChannelDecisionManagerImplTests extends TestCase {
|
||||
public class ChannelDecisionManagerImplTests {
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void testCannotSetEmptyChannelProcessorsList() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
|
||||
@@ -58,7 +58,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
|
||||
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testCannotSetIncorrectObjectTypesIntoChannelProcessorsList()
|
||||
throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
@@ -73,7 +74,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testCannotSetNullChannelProcessorsList() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
|
||||
@@ -86,7 +88,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
|
||||
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testDecideIsOperational() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
|
||||
@@ -107,7 +110,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
|
||||
cdm.decide(fi, cad);
|
||||
assertThat(fi.getResponse().isCommitted()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testAnyChannelAttributeCausesProcessorsToBeSkipped() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", true);
|
||||
@@ -124,7 +128,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
|
||||
cdm.decide(fi, SecurityConfig.createList(new String[] { "abc", "ANY_CHANNEL" }));
|
||||
assertThat(fi.getResponse().isCommitted()).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testDecideIteratesAllProcessorsIfNoneCommitAResponse() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
|
||||
@@ -143,7 +148,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
|
||||
cdm.decide(fi, SecurityConfig.createList("SOME_ATTRIBUTE_NO_PROCESSORS_SUPPORT"));
|
||||
assertThat(fi.getResponse().isCommitted()).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testDelegatesSupports() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
|
||||
@@ -158,7 +164,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
|
||||
assertThat(cdm.supports(new SecurityConfig("abc"))).isTrue();
|
||||
assertThat(cdm.supports(new SecurityConfig("UNSUPPORTED"))).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
assertThat(cdm.getChannelProcessors()).isNull();
|
||||
@@ -172,7 +179,8 @@ public class ChannelDecisionManagerImplTests extends TestCase {
|
||||
|
||||
assertThat(cdm.getChannelProcessors()).isEqualTo(list);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
|
||||
|
||||
@@ -16,11 +16,11 @@
|
||||
package org.springframework.security.web.access.channel;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.access.SecurityConfig;
|
||||
@@ -32,8 +32,9 @@ import org.springframework.security.web.access.channel.InsecureChannelProcessor;
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class InsecureChannelProcessorTests extends TestCase {
|
||||
|
||||
public class InsecureChannelProcessorTests {
|
||||
|
||||
@Test
|
||||
public void testDecideDetectsAcceptableChannel() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
@@ -53,7 +54,8 @@ public class InsecureChannelProcessorTests extends TestCase {
|
||||
|
||||
assertThat(fi.getResponse().isCommitted()).isFalse();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testDecideDetectsUnacceptableChannel() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
@@ -76,7 +78,8 @@ public class InsecureChannelProcessorTests extends TestCase {
|
||||
|
||||
assertThat(fi.getResponse().isCommitted()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testDecideRejectsNulls() throws Exception {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.afterPropertiesSet();
|
||||
@@ -89,7 +92,8 @@ public class InsecureChannelProcessorTests extends TestCase {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
assertThat(processor.getInsecureKeyword()).isEqualTo("REQUIRES_INSECURE_CHANNEL");
|
||||
@@ -100,7 +104,8 @@ public class InsecureChannelProcessorTests extends TestCase {
|
||||
processor.setEntryPoint(null);
|
||||
assertThat(processor.getEntryPoint() == null).isTrue();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testMissingEntryPoint() throws Exception {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.setEntryPoint(null);
|
||||
@@ -113,7 +118,8 @@ public class InsecureChannelProcessorTests extends TestCase {
|
||||
assertThat(expected.getMessage()).isEqualTo("entryPoint required");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testMissingSecureChannelKeyword() throws Exception {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.setInsecureKeyword(null);
|
||||
@@ -136,7 +142,8 @@ public class InsecureChannelProcessorTests extends TestCase {
|
||||
assertThat(expected.getMessage()).isEqualTo("insecureKeyword required");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testSupports() {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
assertThat(processor.supports(new SecurityConfig("REQUIRES_INSECURE_CHANNEL"))).isTrue();
|
||||
|
||||
@@ -16,8 +16,7 @@
|
||||
package org.springframework.security.web.access.channel;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.springframework.security.MockPortResolver;
|
||||
|
||||
@@ -26,7 +25,7 @@ import org.springframework.security.web.PortMapperImpl;
|
||||
import org.springframework.security.web.PortResolver;
|
||||
import org.springframework.security.web.RedirectStrategy;
|
||||
import org.springframework.security.web.access.channel.RetryWithHttpEntryPoint;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
@@ -38,10 +37,10 @@ import java.util.Map;
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class RetryWithHttpEntryPointTests extends TestCase {
|
||||
public class RetryWithHttpEntryPointTests {
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void testDetectsMissingPortMapper() throws Exception {
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
|
||||
@@ -52,7 +51,8 @@ public class RetryWithHttpEntryPointTests extends TestCase {
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testDetectsMissingPortResolver() throws Exception {
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
|
||||
@@ -63,7 +63,8 @@ public class RetryWithHttpEntryPointTests extends TestCase {
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
PortMapper portMapper = mock(PortMapper.class);
|
||||
@@ -76,7 +77,8 @@ public class RetryWithHttpEntryPointTests extends TestCase {
|
||||
assertThat(ep.getPortResolver()).isSameAs(portResolver);
|
||||
assertThat(ep.getRedirectStrategy()).isSameAs(redirector);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello/pathInfo.html");
|
||||
@@ -92,10 +94,10 @@ public class RetryWithHttpEntryPointTests extends TestCase {
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com/bigWebApp/hello/pathInfo.html?open=true",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com/bigWebApp/hello/pathInfo.html?open=true");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testNormalOperationWithNullQueryString() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello");
|
||||
@@ -110,10 +112,10 @@ public class RetryWithHttpEntryPointTests extends TestCase {
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com/bigWebApp/hello");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testOperationWhenTargetPortIsUnknown() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp");
|
||||
request.setQueryString("open=true");
|
||||
@@ -130,7 +132,8 @@ public class RetryWithHttpEntryPointTests extends TestCase {
|
||||
ep.commence(request, response);
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("/bigWebApp?open=true");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testOperationWithNonStandardPort() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello/pathInfo.html");
|
||||
@@ -151,8 +154,7 @@ public class RetryWithHttpEntryPointTests extends TestCase {
|
||||
ep.setPortMapper(portMapper);
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals(
|
||||
"http://www.example.com:8888/bigWebApp/hello/pathInfo.html?open=true",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo(
|
||||
"http://www.example.com:8888/bigWebApp/hello/pathInfo.html?open=true");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,13 +15,13 @@
|
||||
|
||||
package org.springframework.security.web.access.channel;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.springframework.security.MockPortResolver;
|
||||
|
||||
import org.springframework.security.web.PortMapperImpl;
|
||||
import org.springframework.security.web.access.channel.RetryWithHttpsEntryPoint;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
@@ -33,10 +33,10 @@ import java.util.Map;
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class RetryWithHttpsEntryPointTests extends TestCase {
|
||||
public class RetryWithHttpsEntryPointTests {
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void testDetectsMissingPortMapper() throws Exception {
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
|
||||
@@ -48,6 +48,7 @@ public class RetryWithHttpsEntryPointTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectsMissingPortResolver() throws Exception {
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
|
||||
@@ -59,6 +60,7 @@ public class RetryWithHttpsEntryPointTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
@@ -67,6 +69,7 @@ public class RetryWithHttpsEntryPointTests extends TestCase {
|
||||
assertThat(ep.getPortResolver() != null).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello/pathInfo.html");
|
||||
@@ -82,10 +85,11 @@ public class RetryWithHttpsEntryPointTests extends TestCase {
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello/pathInfo.html?open=true",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo(
|
||||
"https://www.example.com/bigWebApp/hello/pathInfo.html?open=true");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNormalOperationWithNullQueryString() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello");
|
||||
@@ -100,10 +104,10 @@ public class RetryWithHttpsEntryPointTests extends TestCase {
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOperationWhenTargetPortIsUnknown() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp");
|
||||
request.setQueryString("open=true");
|
||||
@@ -121,6 +125,7 @@ public class RetryWithHttpsEntryPointTests extends TestCase {
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("/bigWebApp?open=true");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOperationWithNonStandardPort() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello/pathInfo.html");
|
||||
@@ -141,8 +146,7 @@ public class RetryWithHttpsEntryPointTests extends TestCase {
|
||||
ep.setPortMapper(portMapper);
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals(
|
||||
"https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo(
|
||||
"https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,11 +16,11 @@
|
||||
package org.springframework.security.web.access.channel;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.access.SecurityConfig;
|
||||
@@ -32,10 +32,10 @@ import org.springframework.security.web.access.channel.SecureChannelProcessor;
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class SecureChannelProcessorTests extends TestCase {
|
||||
public class SecureChannelProcessorTests {
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void testDecideDetectsAcceptableChannel() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
@@ -57,6 +57,7 @@ public class SecureChannelProcessorTests extends TestCase {
|
||||
assertThat(fi.getResponse().isCommitted()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDecideDetectsUnacceptableChannel() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
@@ -79,6 +80,7 @@ public class SecureChannelProcessorTests extends TestCase {
|
||||
assertThat(fi.getResponse().isCommitted()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDecideRejectsNulls() throws Exception {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.afterPropertiesSet();
|
||||
@@ -92,6 +94,7 @@ public class SecureChannelProcessorTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
assertThat(processor.getSecureKeyword()).isEqualTo("REQUIRES_SECURE_CHANNEL");
|
||||
@@ -103,6 +106,7 @@ public class SecureChannelProcessorTests extends TestCase {
|
||||
assertThat(processor.getEntryPoint() == null).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMissingEntryPoint() throws Exception {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.setEntryPoint(null);
|
||||
@@ -116,6 +120,7 @@ public class SecureChannelProcessorTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMissingSecureChannelKeyword() throws Exception {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.setSecureKeyword(null);
|
||||
@@ -139,6 +144,7 @@ public class SecureChannelProcessorTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSupports() {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
assertThat(processor.supports(new SecurityConfig("REQUIRES_SECURE_CHANNEL"))).isTrue();
|
||||
|
||||
@@ -13,10 +13,10 @@
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.access.expression;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@@ -39,6 +39,7 @@ import org.springframework.security.web.FilterInvocation;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DefaultWebSecurityExpressionHandlerTests {
|
||||
|
||||
@Mock
|
||||
private AuthenticationTrustResolver trustResolver;
|
||||
|
||||
@@ -71,10 +72,10 @@ public class DefaultWebSecurityExpressionHandlerTests {
|
||||
EvaluationContext ctx = handler.createEvaluationContext(
|
||||
mock(Authentication.class), mock(FilterInvocation.class));
|
||||
ExpressionParser parser = handler.getExpressionParser();
|
||||
assertThat(parser.parseExpression("@role.getAttribute() == 'ROLE_A'").isTrue().getValue(
|
||||
ctx, Boolean.class));
|
||||
assertThat(parser.parseExpression("@role.attribute == 'ROLE_A'").isTrue().getValue(ctx,
|
||||
Boolean.class));
|
||||
assertThat(parser.parseExpression("@role.getAttribute() == 'ROLE_A'").getValue(
|
||||
ctx, Boolean.class)).isTrue();
|
||||
assertThat(parser.parseExpression("@role.attribute == 'ROLE_A'").getValue(ctx,
|
||||
Boolean.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
@@ -86,8 +87,8 @@ public class DefaultWebSecurityExpressionHandlerTests {
|
||||
public void createEvaluationContextCustomTrustResolver() {
|
||||
handler.setTrustResolver(trustResolver);
|
||||
|
||||
Expression expression = handler.getExpressionParser()
|
||||
.parseExpression("anonymous");
|
||||
Expression expression = handler.getExpressionParser().parseExpression(
|
||||
"anonymous");
|
||||
EvaluationContext context = handler.createEvaluationContext(authentication,
|
||||
invocation);
|
||||
assertThat(expression.getValue(context, Boolean.class)).isFalse();
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
|
||||
package org.springframework.security.web.access.expression;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.junit.Test;
|
||||
@@ -19,24 +25,19 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public class WebExpressionVoterTests {
|
||||
|
||||
private Authentication user = new TestingAuthenticationToken("user", "pass", "X");
|
||||
|
||||
@Test
|
||||
public void supportsWebConfigAttributeAndFilterInvocation() throws Exception {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertTrue(voter
|
||||
.supports(new WebExpressionConfigAttribute(mock(Expression.class), mock(SecurityEvaluationContextPostProcessor.class))));
|
||||
assertThat(voter.supports(new WebExpressionConfigAttribute(mock(Expression.class),
|
||||
mock(SecurityEvaluationContextPostProcessor.class)))).isTrue();
|
||||
assertThat(voter.supports(FilterInvocation.class)).isTrue();
|
||||
assertThat(voter.supports(MethodInvocation.class)).isFalse();
|
||||
|
||||
@@ -45,23 +46,27 @@ public class WebExpressionVoterTests {
|
||||
@Test
|
||||
public void abstainsIfNoAttributeFound() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertEquals(
|
||||
AccessDecisionVoter.ACCESS_ABSTAIN,
|
||||
voter.vote(user, new FilterInvocation("/path", "GET"),
|
||||
SecurityConfig.createList("A", "B", "C")));
|
||||
assertThat(voter.vote(user, new FilterInvocation("/path", "GET"),
|
||||
SecurityConfig.createList("A", "B", "C"))).isEqualTo(
|
||||
AccessDecisionVoter.ACCESS_ABSTAIN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void grantsAccessIfExpressionIsTrueDeniesIfFalse() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
Expression ex = mock(Expression.class);
|
||||
SecurityEvaluationContextPostProcessor postProcessor = mock(SecurityEvaluationContextPostProcessor.class);
|
||||
when(postProcessor.postProcess(any(EvaluationContext.class), any(FilterInvocation.class))).thenAnswer(new Answer<EvaluationContext>() {
|
||||
public EvaluationContext answer(InvocationOnMock invocation) throws Throwable {
|
||||
return invocation.getArgumentAt(0, EvaluationContext.class);
|
||||
}
|
||||
});
|
||||
WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex,postProcessor);
|
||||
SecurityEvaluationContextPostProcessor postProcessor = mock(
|
||||
SecurityEvaluationContextPostProcessor.class);
|
||||
when(postProcessor.postProcess(any(EvaluationContext.class),
|
||||
any(FilterInvocation.class))).thenAnswer(new Answer<EvaluationContext>() {
|
||||
|
||||
public EvaluationContext answer(InvocationOnMock invocation)
|
||||
throws Throwable {
|
||||
return invocation.getArgumentAt(0, EvaluationContext.class);
|
||||
}
|
||||
});
|
||||
WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex,
|
||||
postProcessor);
|
||||
EvaluationContext ctx = mock(EvaluationContext.class);
|
||||
SecurityExpressionHandler eh = mock(SecurityExpressionHandler.class);
|
||||
FilterInvocation fi = new FilterInvocation("/path", "GET");
|
||||
@@ -73,10 +78,12 @@ public class WebExpressionVoterTests {
|
||||
attributes.addAll(SecurityConfig.createList("A", "B", "C"));
|
||||
attributes.add(weca);
|
||||
|
||||
assertThat(fi).isCloseTo(AccessDecisionVoter.ACCESS_GRANTED, voter.vote(user, within(attributes)));
|
||||
assertThat(voter.vote(user, fi, attributes)).isEqualTo(
|
||||
AccessDecisionVoter.ACCESS_GRANTED);
|
||||
|
||||
// Second time false
|
||||
assertThat(fi).isCloseTo(AccessDecisionVoter.ACCESS_DENIED, voter.vote(user, within(attributes)));
|
||||
assertThat(voter.vote(user, fi, attributes)).isEqualTo(
|
||||
AccessDecisionVoter.ACCESS_DENIED);
|
||||
}
|
||||
|
||||
// SEC-2507
|
||||
@@ -87,6 +94,7 @@ public class WebExpressionVoterTests {
|
||||
}
|
||||
|
||||
private static class FilterInvocationChild extends FilterInvocation {
|
||||
|
||||
public FilterInvocationChild(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) {
|
||||
super(request, response, chain);
|
||||
|
||||
@@ -16,9 +16,6 @@
|
||||
package org.springframework.security.web.authentication;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
@@ -66,7 +63,9 @@ import org.springframework.test.util.ReflectionTestUtils;
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public class AbstractAuthenticationProcessingFilterTests {
|
||||
|
||||
SavedRequestAwareAuthenticationSuccessHandler successHandler;
|
||||
|
||||
SimpleUrlAuthenticationFailureHandler failureHandler;
|
||||
|
||||
// ~ Methods
|
||||
@@ -137,8 +136,9 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
filter.doFilter(request, response, chain);
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("test")
|
||||
.getPrincipal().toString());
|
||||
assertThat(
|
||||
SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo(
|
||||
"test");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -151,8 +151,8 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
assertThat(filter.getRememberMeServices()).isNotNull();
|
||||
filter.setRememberMeServices(new TokenBasedRememberMeServices("key",
|
||||
new AbstractRememberMeServicesTests.MockUserDetailsService()));
|
||||
assertThat(filter.getRememberMeServices().isEqualTo(TokenBasedRememberMeServices.class)
|
||||
.getClass());
|
||||
assertThat(filter.getRememberMeServices().getClass()).isEqualTo(
|
||||
TokenBasedRememberMeServices.class);
|
||||
assertThat(filter.getAuthenticationManager() != null).isTrue();
|
||||
}
|
||||
|
||||
@@ -196,7 +196,8 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
|
||||
|
||||
filter.setFilterProcessesUrl("/j_mock_post");
|
||||
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
|
||||
filter.setSessionAuthenticationStrategy(
|
||||
mock(SessionAuthenticationStrategy.class));
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
@@ -206,8 +207,9 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
filter.doFilter(request, response, chain);
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("test")
|
||||
.getPrincipal().toString());
|
||||
assertThat(
|
||||
SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo(
|
||||
"test");
|
||||
// Should still have the same session
|
||||
assertThat(request.getSession()).isEqualTo(sessionPreAuth);
|
||||
}
|
||||
@@ -225,7 +227,8 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertThat(expected.getMessage()).isEqualTo("authenticationManager must be specified");
|
||||
assertThat(expected.getMessage()).isEqualTo(
|
||||
"authenticationManager must be specified");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,7 +244,8 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertThat(expected.getMessage()).isEqualTo("Pattern cannot be null or empty");
|
||||
assertThat(expected.getMessage()).isEqualTo(
|
||||
"Pattern cannot be null or empty");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -268,8 +272,9 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
filter.doFilter(request, response, chain);
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("test")
|
||||
.getPrincipal().toString());
|
||||
assertThat(
|
||||
SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo(
|
||||
"test");
|
||||
|
||||
// Now try again but this time have filter deny access
|
||||
// Setup our HTTP request
|
||||
@@ -305,7 +310,8 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
// Setup our test object, to grant access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
|
||||
filter.setFilterProcessesUrl("/j_mock_post");
|
||||
AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class);
|
||||
AuthenticationSuccessHandler successHandler = mock(
|
||||
AuthenticationSuccessHandler.class);
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
// Test
|
||||
@@ -332,7 +338,8 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
|
||||
// Setup our test object, to deny access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
|
||||
AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class);
|
||||
AuthenticationFailureHandler failureHandler = mock(
|
||||
AuthenticationFailureHandler.class);
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
|
||||
// Test
|
||||
@@ -413,15 +420,19 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
// ~ Inner Classes
|
||||
// ==================================================================================================
|
||||
|
||||
private class MockAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
|
||||
private class MockAuthenticationFilter
|
||||
extends AbstractAuthenticationProcessingFilter {
|
||||
|
||||
private AuthenticationException exceptionToThrow;
|
||||
|
||||
private boolean grantAccess;
|
||||
|
||||
public MockAuthenticationFilter(boolean grantAccess) {
|
||||
this();
|
||||
setRememberMeServices(new NullRememberMeServices());
|
||||
this.grantAccess = grantAccess;
|
||||
this.exceptionToThrow = new BadCredentialsException("Mock requested to do so");
|
||||
this.exceptionToThrow = new BadCredentialsException(
|
||||
"Mock requested to do so");
|
||||
}
|
||||
|
||||
private MockAuthenticationFilter() {
|
||||
@@ -441,6 +452,7 @@ public class AbstractAuthenticationProcessingFilterTests {
|
||||
}
|
||||
|
||||
private class MockFilterChain implements FilterChain {
|
||||
|
||||
private boolean expectToProceed;
|
||||
|
||||
public MockFilterChain(boolean expectToProceed) {
|
||||
|
||||
@@ -102,7 +102,7 @@ public class AnonymousAuthenticationFilterTests {
|
||||
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
assertThat(auth.getPrincipal()).isEqualTo("anonymousUsername");
|
||||
assertThat(AuthorityUtils.authorityListToSet(auth.getAuthorities()).isTrue().contains(
|
||||
assertThat(AuthorityUtils.authorityListToSet(auth.getAuthorities()).contains(
|
||||
"ROLE_ANONYMOUS"));
|
||||
SecurityContextHolder.getContext().setAuthentication(null); // so anonymous fires
|
||||
// again
|
||||
|
||||
@@ -93,22 +93,19 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello");
|
||||
|
||||
request.setServerPort(8080);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:8443/bigWebApp/hello");
|
||||
|
||||
// Now test an unusual custom HTTP:HTTPS is handled properly
|
||||
request.setServerPort(8888);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:8443/bigWebApp/hello");
|
||||
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
@@ -124,8 +121,7 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:9999/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:9999/bigWebApp/hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -148,15 +144,13 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello");
|
||||
|
||||
request.setServerPort(8443);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:8443/bigWebApp/hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -178,8 +172,7 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("http://www.example.com/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com/bigWebApp/hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -204,8 +197,7 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
|
||||
// Response doesn't switch to HTTPS, as we didn't know HTTP port 8888 to HTTP port
|
||||
// mapping
|
||||
assertEquals("http://www.example.com:8888/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("http://www.example.com:8888/bigWebApp/hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -250,8 +242,7 @@ public class LoginUrlAuthenticationEntryPointTests {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com/bigWebApp/some_path",
|
||||
response.getRedirectedUrl());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/some_path");
|
||||
}
|
||||
|
||||
// SEC-1498
|
||||
|
||||
@@ -40,8 +40,7 @@ public class SimpleUrlAuthenticationFailureHandlerTests {
|
||||
AuthenticationException e = mock(AuthenticationException.class);
|
||||
|
||||
afh.onAuthenticationFailure(request, response, e);
|
||||
assertSame(e,
|
||||
request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION));
|
||||
assertThat(request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isSameAs(e);
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("/target");
|
||||
}
|
||||
|
||||
|
||||
@@ -17,11 +17,10 @@ package org.springframework.security.web.authentication;
|
||||
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
@@ -37,7 +36,7 @@ import org.springframework.security.core.AuthenticationException;
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class UsernamePasswordAuthenticationFilterTests extends TestCase {
|
||||
public class UsernamePasswordAuthenticationFilterTests {
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@@ -58,8 +57,7 @@ public class UsernamePasswordAuthenticationFilterTests extends TestCase {
|
||||
Authentication result = filter.attemptAuthentication(request,
|
||||
new MockHttpServletResponse());
|
||||
assertThat(result != null).isTrue();
|
||||
assertEquals("127.0.0.1",
|
||||
((WebAuthenticationDetails) result.getDetails()).getRemoteAddress());
|
||||
assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -71,8 +69,8 @@ public class UsernamePasswordAuthenticationFilterTests extends TestCase {
|
||||
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
assertNotNull(filter
|
||||
.attemptAuthentication(request, new MockHttpServletResponse()));
|
||||
assertThat(filter
|
||||
.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -84,8 +82,8 @@ public class UsernamePasswordAuthenticationFilterTests extends TestCase {
|
||||
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
assertNotNull(filter
|
||||
.attemptAuthentication(request, new MockHttpServletResponse()));
|
||||
assertThat(filter
|
||||
.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -102,8 +100,7 @@ public class UsernamePasswordAuthenticationFilterTests extends TestCase {
|
||||
Authentication result = filter.attemptAuthentication(request,
|
||||
new MockHttpServletResponse());
|
||||
assertThat(result).isNotNull();
|
||||
assertEquals("127.0.0.1",
|
||||
((WebAuthenticationDetails) result.getDetails()).getRemoteAddress());
|
||||
assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -13,12 +13,13 @@
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.authentication.logout;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
@@ -47,7 +48,8 @@ public class HttpStatusReturningLogoutSuccessHandlerTests {
|
||||
|
||||
@Test
|
||||
public void testCustomHttpStatusBeingReturned() throws Exception {
|
||||
final HttpStatusReturningLogoutSuccessHandler lsh = new HttpStatusReturningLogoutSuccessHandler(HttpStatus.NO_CONTENT);
|
||||
final HttpStatusReturningLogoutSuccessHandler lsh = new HttpStatusReturningLogoutSuccessHandler(
|
||||
HttpStatus.NO_CONTENT);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@@ -71,7 +73,7 @@ public class HttpStatusReturningLogoutSuccessHandlerTests {
|
||||
return;
|
||||
}
|
||||
|
||||
Assert.fail("Expected an IllegalArgumentException to be thrown.");
|
||||
fail("Expected an IllegalArgumentException to be thrown.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package org.springframework.security.web.authentication.logout;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.web.authentication.logout.LogoutFilter;
|
||||
@@ -11,13 +13,14 @@ import org.springframework.security.web.firewall.DefaultHttpFirewall;
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class LogoutHandlerTests extends TestCase {
|
||||
public class LogoutHandlerTests {
|
||||
LogoutFilter filter;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
filter = new LogoutFilter("/success", new SecurityContextLogoutHandler());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequiresLogoutUrlWorksWithPathParams() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@@ -30,6 +33,7 @@ public class LogoutHandlerTests extends TestCase {
|
||||
assertThat(filter.requiresLogout(fw.getFirewalledRequest(request), response)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequiresLogoutUrlWorksWithQueryParams() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("/context");
|
||||
|
||||
@@ -13,8 +13,6 @@
|
||||
package org.springframework.security.web.authentication.preauth;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -158,8 +156,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
|
||||
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(),
|
||||
new MockFilterChain());
|
||||
|
||||
assertThat(SecurityContextHolder.getContext().isEqualTo(authentication)
|
||||
.getAuthentication());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(
|
||||
authentication);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -332,8 +330,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest();
|
||||
MockHttpServletResponse res = new MockHttpServletResponse();
|
||||
getFilter(grantAccess).doFilter(req, res, new MockFilterChain());
|
||||
assertThat(null != SecurityContextHolder.getContext().isEqualTo(grantAccess)
|
||||
.getAuthentication());
|
||||
assertThat(null != SecurityContextHolder.getContext().getAuthentication()).isEqualTo(
|
||||
grantAccess);
|
||||
}
|
||||
|
||||
private static ConcretePreAuthenticatedProcessingFilter getFilter(boolean grantAccess)
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
|
||||
package org.springframework.security.web.authentication.preauth;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
|
||||
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
|
||||
|
||||
public class Http403ForbiddenEntryPointTests extends TestCase {
|
||||
public class Http403ForbiddenEntryPointTests {
|
||||
|
||||
public void testCommence() {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest();
|
||||
@@ -22,7 +23,7 @@ public class Http403ForbiddenEntryPointTests extends TestCase {
|
||||
try {
|
||||
fep.commence(req, resp,
|
||||
new AuthenticationCredentialsNotFoundException("test"));
|
||||
assertThat(resp.getStatus().isEqualTo("Incorrect status"),
|
||||
assertThat(resp.getStatus()).withFailMessage("Incorrect status").isEqualTo(
|
||||
HttpServletResponse.SC_FORBIDDEN);
|
||||
}
|
||||
catch (IOException e) {
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
|
||||
package org.springframework.security.web.authentication.preauth;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
@@ -14,8 +11,6 @@ import org.springframework.security.core.userdetails.AuthenticationUserDetailsSe
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
|
||||
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -45,7 +40,8 @@ public class PreAuthenticatedAuthenticationProviderTests {
|
||||
@Test
|
||||
public final void nullPrincipalReturnsNullAuthentication() throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
|
||||
Authentication request = new PreAuthenticatedAuthenticationToken(null, "dummyPwd");
|
||||
Authentication request = new PreAuthenticatedAuthenticationToken(null,
|
||||
"dummyPwd");
|
||||
Authentication result = provider.authenticate(request);
|
||||
assertThat(result).isNull();
|
||||
}
|
||||
@@ -108,7 +104,8 @@ public class PreAuthenticatedAuthenticationProviderTests {
|
||||
private PreAuthenticatedAuthenticationProvider getProvider(UserDetails aUserDetails)
|
||||
throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider result = new PreAuthenticatedAuthenticationProvider();
|
||||
result.setPreAuthenticatedUserDetailsService(getPreAuthenticatedUserDetailsService(aUserDetails));
|
||||
result.setPreAuthenticatedUserDetailsService(
|
||||
getPreAuthenticatedUserDetailsService(aUserDetails));
|
||||
result.afterPropertiesSet();
|
||||
return result;
|
||||
}
|
||||
@@ -116,6 +113,7 @@ public class PreAuthenticatedAuthenticationProviderTests {
|
||||
private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getPreAuthenticatedUserDetailsService(
|
||||
final UserDetails aUserDetails) {
|
||||
return new AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken>() {
|
||||
|
||||
public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token)
|
||||
throws UsernameNotFoundException {
|
||||
if (aUserDetails != null
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
|
||||
package org.springframework.security.web.authentication.preauth;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author TSARDD
|
||||
* @since 18-okt-2007
|
||||
*/
|
||||
public class PreAuthenticatedAuthenticationTokenTests extends TestCase {
|
||||
public class PreAuthenticatedAuthenticationTokenTests {
|
||||
|
||||
@Test
|
||||
public void testPreAuthenticatedAuthenticationTokenRequestWithDetails() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
@@ -29,6 +31,7 @@ public class PreAuthenticatedAuthenticationTokenTests extends TestCase {
|
||||
assertThat(token.getAuthorities().isEmpty()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPreAuthenticatedAuthenticationTokenRequestWithoutDetails() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
@@ -40,6 +43,7 @@ public class PreAuthenticatedAuthenticationTokenTests extends TestCase {
|
||||
assertThat(token.getAuthorities().isEmpty()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPreAuthenticatedAuthenticationTokenResponse() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
@@ -51,9 +55,11 @@ public class PreAuthenticatedAuthenticationTokenTests extends TestCase {
|
||||
assertThat(token.getDetails()).isNull();
|
||||
assertThat(token.getAuthorities()).isNotNull();
|
||||
Collection<GrantedAuthority> resultColl = token.getAuthorities();
|
||||
assertTrue("GrantedAuthority collections do not match; result: " + resultColl
|
||||
+ ", expected: " + gas,
|
||||
gas.containsAll(resultColl) && resultColl.containsAll(gas));
|
||||
assertThat(
|
||||
|
||||
gas.containsAll(resultColl) && resultColl.containsAll(gas)).withFailMessage(
|
||||
"GrantedAuthority collections do not match; result: " + resultColl
|
||||
+ ", expected: " + gas).isTrue();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -68,11 +68,8 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {
|
||||
// PreAuthenticatedGrantedAuthoritiesUserDetailsService
|
||||
// assertThat(password).isEqualTo(ud.getPassword());
|
||||
|
||||
assertTrue(
|
||||
"GrantedAuthority collections do not match; result: "
|
||||
+ ud.getAuthorities() + ", expected: " + gas,
|
||||
gas.containsAll(ud.getAuthorities())
|
||||
&& ud.getAuthorities().containsAll(gas));
|
||||
assertThat(gas.containsAll(ud.getAuthorities())
|
||||
&& ud.getAuthorities().containsAll(gas)).withFailMessage("GrantedAuthority collections do not match; result: "+ ud.getAuthorities() + ", expected: " + gas).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package org.springframework.security.web.authentication.preauth;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
@@ -33,9 +33,9 @@ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests {
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
|
||||
getRequest("testUser", new String[] {}), gas);
|
||||
List<GrantedAuthority> returnedGas = details.getGrantedAuthorities();
|
||||
assertTrue("Collections do not contain same elements; expected: " + gas
|
||||
+ ", returned: " + returnedGas, gas.containsAll(returnedGas)
|
||||
&& returnedGas.containsAll(gas));
|
||||
assertThat(gas.containsAll(returnedGas) && returnedGas.containsAll(gas))
|
||||
.withFailMessage("Collections do not contain same elements; expected: " + gas
|
||||
+ ", returned: " + returnedGas).isTrue();
|
||||
}
|
||||
|
||||
private HttpServletRequest getRequest(final String userName, final String[] aRoles) {
|
||||
|
||||
@@ -51,10 +51,8 @@ public class RequestHeaderAuthenticationFilterTests {
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("cat")
|
||||
.getName());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("N/A")
|
||||
.getCredentials());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("cat");
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("N/A");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -69,8 +67,7 @@ public class RequestHeaderAuthenticationFilterTests {
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().isEqualTo("wolfman")
|
||||
.getName());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("wolfman");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -86,8 +83,7 @@ public class RequestHeaderAuthenticationFilterTests {
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(SecurityContextHolder.getContext().isEqualTo("catspassword")
|
||||
.getAuthentication().getCredentials());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("catspassword");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
|
||||
package org.springframework.security.web.authentication.preauth.j2ee;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
@@ -8,8 +12,7 @@ import java.util.Set;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.mapping.Attributes2GrantedAuthoritiesMapper;
|
||||
@@ -22,9 +25,9 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedG
|
||||
*
|
||||
* @author TSARDD
|
||||
*/
|
||||
public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extends
|
||||
TestCase {
|
||||
public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
|
||||
|
||||
@Test
|
||||
public final void testAfterPropertiesSetException() {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
|
||||
try {
|
||||
@@ -38,6 +41,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void testBuildDetailsHttpServletRequestNoMappedNoUserRoles() {
|
||||
String[] mappedRoles = new String[] {};
|
||||
String[] roles = new String[] {};
|
||||
@@ -45,6 +49,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void testBuildDetailsHttpServletRequestNoMappedUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] {};
|
||||
String[] roles = new String[] { "Role1", "Role2" };
|
||||
@@ -52,6 +57,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void testBuildDetailsHttpServletRequestNoUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] {};
|
||||
@@ -59,6 +65,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void testBuildDetailsHttpServletRequestAllUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
@@ -66,6 +73,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void testBuildDetailsHttpServletRequestUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4", "Role5" };
|
||||
@@ -73,6 +81,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void testBuildDetailsHttpServletRequestPartialUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role2", "Role3" };
|
||||
@@ -80,6 +89,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void testBuildDetailsHttpServletRequestPartialAndUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role2", "Role3", "Role5" };
|
||||
@@ -89,13 +99,14 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend
|
||||
|
||||
private void testDetails(String[] mappedRoles, String[] userRoles,
|
||||
String[] expectedRoles) {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource src = getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(mappedRoles);
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource src = getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(
|
||||
mappedRoles);
|
||||
Object o = src.buildDetails(getRequest("testUser", userRoles));
|
||||
assertThat(o).isNotNull();
|
||||
assertTrue(
|
||||
"Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: "
|
||||
+ o.getClass(),
|
||||
o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails);
|
||||
assertThat(
|
||||
o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails).withFailMessage(
|
||||
"Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: "
|
||||
+ o.getClass()).isTrue();
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = (PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails) o;
|
||||
List<GrantedAuthority> gas = details.getGrantedAuthorities();
|
||||
assertThat(gas).as("Granted authorities should not be null").isNotNull();
|
||||
@@ -106,17 +117,17 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend
|
||||
for (int i = 0; i < gas.size(); i++) {
|
||||
gasRolesSet.add(gas.get(i).getAuthority());
|
||||
}
|
||||
assertTrue(
|
||||
"Granted Authorities do not match expected roles",
|
||||
expectedRolesColl.containsAll(gasRolesSet)
|
||||
&& gasRolesSet.containsAll(expectedRolesColl));
|
||||
assertThat(expectedRolesColl.containsAll(gasRolesSet)
|
||||
&& gasRolesSet.containsAll(expectedRolesColl)).withFailMessage(
|
||||
"Granted Authorities do not match expected roles").isTrue();
|
||||
}
|
||||
|
||||
private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(
|
||||
String[] mappedRoles) {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
|
||||
result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles));
|
||||
result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper());
|
||||
result.setUserRoles2GrantedAuthoritiesMapper(
|
||||
getJ2eeUserRoles2GrantedAuthoritiesMapper());
|
||||
|
||||
try {
|
||||
result.afterPropertiesSet();
|
||||
@@ -144,6 +155,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extend
|
||||
|
||||
private HttpServletRequest getRequest(final String userName, final String[] aRoles) {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
|
||||
private Set<String> roles = new HashSet<String>(Arrays.asList(aRoles));
|
||||
|
||||
public boolean isUserInRole(String arg0) {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
|
||||
package org.springframework.security.web.authentication.preauth.j2ee;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
@@ -7,35 +10,35 @@ import java.util.Set;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthenticatedProcessingFilter;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author TSARDD
|
||||
* @since 18-okt-2007
|
||||
*/
|
||||
public class J2eePreAuthenticatedProcessingFilterTests extends TestCase {
|
||||
public class J2eePreAuthenticatedProcessingFilterTests {
|
||||
|
||||
@Test
|
||||
public final void testGetPreAuthenticatedPrincipal() {
|
||||
String user = "testUser";
|
||||
assertEquals(user,
|
||||
new J2eePreAuthenticatedProcessingFilter()
|
||||
.getPreAuthenticatedPrincipal(getRequest(user, new String[] {})));
|
||||
assertThat(user).isEqualTo(
|
||||
new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedPrincipal(
|
||||
getRequest(user, new String[] {})));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void testGetPreAuthenticatedCredentials() {
|
||||
assertEquals("N/A",
|
||||
new J2eePreAuthenticatedProcessingFilter()
|
||||
.getPreAuthenticatedCredentials(getRequest("testUser",
|
||||
new String[] {})));
|
||||
assertThat("N/A").isEqualTo(
|
||||
new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedCredentials(
|
||||
getRequest("testUser", new String[] {})));
|
||||
}
|
||||
|
||||
private final HttpServletRequest getRequest(final String aUserName,
|
||||
final String[] aRoles) {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
|
||||
private Set<String> roles = new HashSet<String>(Arrays.asList(aRoles));
|
||||
|
||||
public boolean isUserInRole(String arg0) {
|
||||
@@ -44,6 +47,7 @@ public class J2eePreAuthenticatedProcessingFilterTests extends TestCase {
|
||||
};
|
||||
req.setRemoteUser(aUserName);
|
||||
req.setUserPrincipal(new Principal() {
|
||||
|
||||
public String getName() {
|
||||
return aUserName;
|
||||
}
|
||||
|
||||
@@ -33,12 +33,10 @@ public class WebXmlJ2eeDefinedRolesRetrieverTests {
|
||||
rolesRetriever.afterPropertiesSet();
|
||||
Set<String> j2eeRoles = rolesRetriever.getMappableAttributes();
|
||||
assertThat(j2eeRoles).isNotNull();
|
||||
assertThat("J2eeRoles expected size: " + ROLE1TO4_EXPECTED_ROLES.size().isTrue()
|
||||
+ ", actual size: " + j2eeRoles.size(),
|
||||
j2eeRoles.size() == ROLE1TO4_EXPECTED_ROLES.size());
|
||||
assertThat("J2eeRoles expected contents (arbitrary order).isTrue(): "
|
||||
+ ROLE1TO4_EXPECTED_ROLES + ", actual content: " + j2eeRoles,
|
||||
j2eeRoles.containsAll(ROLE1TO4_EXPECTED_ROLES));
|
||||
assertThat(j2eeRoles.size()).withFailMessage("J2eeRoles expected size: " + ROLE1TO4_EXPECTED_ROLES.size()
|
||||
+ ", actual size: " + j2eeRoles.size()).isEqualTo(ROLE1TO4_EXPECTED_ROLES.size());
|
||||
assertThat(j2eeRoles).withFailMessage("J2eeRoles expected contents (arbitrary order).isTrue(): "
|
||||
+ ROLE1TO4_EXPECTED_ROLES + ", actual content: " + j2eeRoles).containsAll(ROLE1TO4_EXPECTED_ROLES);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -56,7 +54,6 @@ public class WebXmlJ2eeDefinedRolesRetrieverTests {
|
||||
});
|
||||
rolesRetriever.afterPropertiesSet();
|
||||
Set<String> j2eeRoles = rolesRetriever.getMappableAttributes();
|
||||
assertThat(actual size: " + j2eeRoles.size().isEqualTo("J2eeRoles expected size: 0), 0,
|
||||
j2eeRoles.size());
|
||||
assertThat(j2eeRoles).withFailMessage("actual size: " + j2eeRoles.size() + "J2eeRoles expected size: 0").isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,10 +34,10 @@ public class WebSpherePreAuthenticatedProcessingFilterTests {
|
||||
when(helper.getCurrentUserName()).thenReturn("jerry");
|
||||
WebSpherePreAuthenticatedProcessingFilter filter = new WebSpherePreAuthenticatedProcessingFilter(
|
||||
helper);
|
||||
assertEquals("jerry",
|
||||
filter.getPreAuthenticatedPrincipal(new MockHttpServletRequest()));
|
||||
assertEquals("N/A",
|
||||
filter.getPreAuthenticatedCredentials(new MockHttpServletRequest()));
|
||||
assertThat(filter.getPreAuthenticatedPrincipal(new MockHttpServletRequest())).isEqualTo(
|
||||
"jerry");
|
||||
assertThat(filter.getPreAuthenticatedCredentials(new MockHttpServletRequest())).isEqualTo(
|
||||
"N/A");
|
||||
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(any(Authentication.class))).thenAnswer(
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package org.springframework.security.web.authentication.preauth.x509;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.core.SpringSecurityMessageSource;
|
||||
import org.springframework.security.web.authentication.preauth.x509.SubjectDnX509PrincipalExtractor;
|
||||
@@ -7,8 +9,6 @@ import org.springframework.security.web.authentication.preauth.x509.SubjectDnX50
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
|
||||
import static junit.framework.Assert.*;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
|
||||
package org.springframework.security.web.authentication.rememberme;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.powermock.api.mockito.PowerMockito.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.powermock.api.mockito.PowerMockito.spy;
|
||||
import static org.powermock.api.mockito.PowerMockito.when;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -17,8 +12,7 @@ import javax.servlet.http.HttpServletResponse;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.mockito.Mockito;
|
||||
import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
@@ -43,6 +37,7 @@ import org.springframework.util.StringUtils;
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareOnlyThisForTest(ReflectionUtils.class)
|
||||
public class AbstractRememberMeServicesTests {
|
||||
|
||||
static User joe = new User("joe", "password", true, true, true, true,
|
||||
AuthorityUtils.createAuthorityList("ROLE_A"));
|
||||
|
||||
@@ -71,7 +66,7 @@ public class AbstractRememberMeServicesTests {
|
||||
services.setTokenValiditySeconds(600);
|
||||
assertThat(services.getTokenValiditySeconds()).isEqualTo(600);
|
||||
assertThat(services.getUserDetailsService()).isSameAs(uds);
|
||||
AuthenticationDetailsSource ads = mock(AuthenticationDetailsSource.class);
|
||||
AuthenticationDetailsSource ads = Mockito.mock(AuthenticationDetailsSource.class);
|
||||
services.setAuthenticationDetailsSource(ads);
|
||||
assertThat(services.getAuthenticationDetailsSource()).isSameAs(ads);
|
||||
services.afterPropertiesSet();
|
||||
@@ -97,7 +92,7 @@ public class AbstractRememberMeServicesTests {
|
||||
@Test
|
||||
public void cookieWithOpenIDidentifierAsNameIsEncodedAndDecoded() throws Exception {
|
||||
String[] cookie = new String[] { "http://id.openid.zz", "cookie", "tokens",
|
||||
"blah" };
|
||||
"blah" };
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
String[] decoded = services.decodeCookie(services.encodeCookie(cookie));
|
||||
@@ -120,16 +115,16 @@ public class AbstractRememberMeServicesTests {
|
||||
assertThat(services.autoLogin(request, response)).isNull();
|
||||
|
||||
// shouldn't try to invalidate our cookie
|
||||
assertNull(response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
|
||||
assertThat(response.getCookie(
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
|
||||
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
// set non-login cookie
|
||||
request.setCookies(new Cookie("mycookie", "cookie"));
|
||||
assertThat(services.autoLogin(request, response)).isNull();
|
||||
assertNull(response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
|
||||
assertThat(response.getCookie(
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -155,7 +150,8 @@ public class AbstractRememberMeServicesTests {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setCookies(new Cookie(
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "ZZZ"));
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
"ZZZ"));
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
assertThat(result).isNull();
|
||||
assertCookieCancelled(response);
|
||||
@@ -248,7 +244,7 @@ public class AbstractRememberMeServicesTests {
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.logout(request, response, mock(Authentication.class));
|
||||
services.logout(request, response, Mockito.mock(Authentication.class));
|
||||
// Try again with null Authentication
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
@@ -260,6 +256,7 @@ public class AbstractRememberMeServicesTests {
|
||||
@Test(expected = CookieTheftException.class)
|
||||
public void cookieTheftExceptionShouldBeRethrown() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
|
||||
protected UserDetails processAutoLoginCookie(String[] cookieTokens,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
throw new CookieTheftException("Pretending cookie was stolen");
|
||||
@@ -318,6 +315,7 @@ public class AbstractRememberMeServicesTests {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
request.setContextPath("contextpath");
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
|
||||
protected String encodeCookie(String[] cookieTokens) {
|
||||
return cookieTokens[0];
|
||||
}
|
||||
@@ -340,28 +338,29 @@ public class AbstractRememberMeServicesTests {
|
||||
request.setContextPath("contextpath");
|
||||
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
|
||||
protected String encodeCookie(String[] cookieTokens) {
|
||||
return cookieTokens[0];
|
||||
}
|
||||
};
|
||||
services.setUseSecureCookie(true);
|
||||
services.setCookie(new String[] { "mycookie" }, 1000, request, response);
|
||||
Cookie cookie = response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
Cookie cookie = response.getCookie(
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(cookie.getSecure()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setHttpOnlyIgnoredForServlet25() throws Exception {
|
||||
spy(ReflectionUtils.class);
|
||||
when(ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class))
|
||||
.thenReturn(null);
|
||||
when(ReflectionUtils.findMethod(Cookie.class, "setHttpOnly",
|
||||
boolean.class)).thenReturn(null);
|
||||
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
assertThat(ReflectionTestUtils.getField(services, "setHttpOnlyMethod")).isNull();
|
||||
|
||||
services = new MockRememberMeServices("key", new MockUserDetailsService(joe,
|
||||
false));
|
||||
services = new MockRememberMeServices("key",
|
||||
new MockUserDetailsService(joe, false));
|
||||
assertThat(ReflectionTestUtils.getField(services, "setHttpOnlyMethod")).isNull();
|
||||
}
|
||||
|
||||
@@ -374,8 +373,8 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
services.setCookie(new String[] { "value" }, 0, request, response);
|
||||
|
||||
Cookie cookie = response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
Cookie cookie = response.getCookie(
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(cookie.getVersion()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@@ -388,8 +387,8 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
services.setCookie(new String[] { "value" }, -1, request, response);
|
||||
|
||||
Cookie cookie = response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
Cookie cookie = response.getCookie(
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(cookie.getVersion()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@@ -402,8 +401,8 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
services.setCookie(new String[] { "value" }, 1, request, response);
|
||||
|
||||
Cookie cookie = response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
Cookie cookie = response.getCookie(
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(cookie.getVersion()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@@ -411,15 +410,15 @@ public class AbstractRememberMeServicesTests {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
Cookie cookie = new Cookie(
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
services.encodeCookie(StringUtils.delimitedListToStringArray(cookieToken,
|
||||
":")));
|
||||
services.encodeCookie(
|
||||
StringUtils.delimitedListToStringArray(cookieToken, ":")));
|
||||
|
||||
return new Cookie[] { cookie };
|
||||
}
|
||||
|
||||
private void assertCookieCancelled(MockHttpServletResponse response) {
|
||||
Cookie returnedCookie = response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
Cookie returnedCookie = response.getCookie(
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(returnedCookie).isNotNull();
|
||||
assertThat(returnedCookie.getMaxAge()).isEqualTo(0);
|
||||
}
|
||||
@@ -428,6 +427,7 @@ public class AbstractRememberMeServicesTests {
|
||||
// ==================================================================================================
|
||||
|
||||
static class MockRememberMeServices extends AbstractRememberMeServices {
|
||||
|
||||
boolean loginSuccessCalled;
|
||||
|
||||
MockRememberMeServices(String key, UserDetailsService userDetailsService) {
|
||||
@@ -449,7 +449,7 @@ public class AbstractRememberMeServicesTests {
|
||||
|
||||
protected UserDetails processAutoLoginCookie(String[] cookieTokens,
|
||||
HttpServletRequest request, HttpServletResponse response)
|
||||
throws RememberMeAuthenticationException {
|
||||
throws RememberMeAuthenticationException {
|
||||
if (cookieTokens.length != 3) {
|
||||
throw new InvalidCookieException("deliberate exception");
|
||||
}
|
||||
@@ -461,7 +461,9 @@ public class AbstractRememberMeServicesTests {
|
||||
}
|
||||
|
||||
public static class MockUserDetailsService implements UserDetailsService {
|
||||
|
||||
private UserDetails toReturn;
|
||||
|
||||
private boolean throwException;
|
||||
|
||||
public MockUserDetailsService() {
|
||||
|
||||
@@ -13,14 +13,20 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.authentication.rememberme;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -44,17 +50,20 @@ import org.springframework.test.util.ReflectionTestUtils;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class JdbcTokenRepositoryImplTests {
|
||||
|
||||
@Mock
|
||||
private Log logger;
|
||||
|
||||
private static SingleConnectionDataSource dataSource;
|
||||
|
||||
private JdbcTokenRepositoryImpl repo;
|
||||
|
||||
private JdbcTemplate template;
|
||||
|
||||
@BeforeClass
|
||||
public static void createDataSource() {
|
||||
dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:tokenrepotest",
|
||||
"sa", "", true);
|
||||
dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:tokenrepotest", "sa",
|
||||
"", true);
|
||||
dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
|
||||
}
|
||||
|
||||
@@ -71,8 +80,9 @@ public class JdbcTokenRepositoryImplTests {
|
||||
repo.setDataSource(dataSource);
|
||||
repo.initDao();
|
||||
template = repo.getJdbcTemplate();
|
||||
template.execute("create table persistent_logins (username varchar(100) not null, "
|
||||
+ "series varchar(100) not null, token varchar(500) not null, last_used timestamp not null)");
|
||||
template.execute(
|
||||
"create table persistent_logins (username varchar(100) not null, "
|
||||
+ "series varchar(100) not null, token varchar(500) not null, last_used timestamp not null)");
|
||||
}
|
||||
|
||||
@After
|
||||
@@ -82,13 +92,13 @@ public class JdbcTokenRepositoryImplTests {
|
||||
|
||||
@Test
|
||||
public void createNewTokenInsertsCorrectData() {
|
||||
Date currentDate = new Date();
|
||||
Timestamp currentDate = new Timestamp(Calendar.getInstance().getTimeInMillis());
|
||||
PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser",
|
||||
"joesseries", "atoken", currentDate);
|
||||
repo.createNewToken(token);
|
||||
|
||||
Map<String, Object> results = template
|
||||
.queryForMap("select * from persistent_logins");
|
||||
Map<String, Object> results = template.queryForMap(
|
||||
"select * from persistent_logins");
|
||||
|
||||
assertThat(results.get("last_used")).isEqualTo(currentDate);
|
||||
assertThat(results.get("username")).isEqualTo("joeuser");
|
||||
@@ -99,25 +109,30 @@ public class JdbcTokenRepositoryImplTests {
|
||||
@Test
|
||||
public void retrievingTokenReturnsCorrectData() {
|
||||
|
||||
template.execute("insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
|
||||
template.execute(
|
||||
"insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
|
||||
PersistentRememberMeToken token = repo.getTokenForSeries("joesseries");
|
||||
|
||||
assertThat(token.getUsername()).isEqualTo("joeuser");
|
||||
assertThat(token.getSeries()).isEqualTo("joesseries");
|
||||
assertThat(token.getTokenValue()).isEqualTo("atoken");
|
||||
assertThat(token.getDate()).isEqualTo(Timestamp.valueOf("2007-10-09 18:19:25.000000000"));
|
||||
assertThat(token.getDate()).isEqualTo(
|
||||
Timestamp.valueOf("2007-10-09 18:19:25.000000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void retrievingTokenWithDuplicateSeriesReturnsNull() {
|
||||
template.execute("insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')");
|
||||
template.execute("insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
|
||||
template.execute(
|
||||
"insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')");
|
||||
template.execute(
|
||||
"insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
|
||||
|
||||
// List results =
|
||||
// template.queryForList("select * from persistent_logins where series = 'joesseries'");
|
||||
// template.queryForList("select * from persistent_logins where series =
|
||||
// 'joesseries'");
|
||||
|
||||
assertThat(repo.getTokenForSeries("joesseries")).isNull();
|
||||
}
|
||||
@@ -138,18 +153,21 @@ public class JdbcTokenRepositoryImplTests {
|
||||
|
||||
@Test
|
||||
public void removingUserTokensDeletesData() {
|
||||
template.execute("insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries2', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')");
|
||||
template.execute("insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
|
||||
template.execute(
|
||||
"insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries2', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')");
|
||||
template.execute(
|
||||
"insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
|
||||
|
||||
// List results =
|
||||
// template.queryForList("select * from persistent_logins where series = 'joesseries'");
|
||||
// template.queryForList("select * from persistent_logins where series =
|
||||
// 'joesseries'");
|
||||
|
||||
repo.removeUserTokens("joeuser");
|
||||
|
||||
List<Map<String, Object>> results = template
|
||||
.queryForList("select * from persistent_logins where username = 'joeuser'");
|
||||
List<Map<String, Object>> results = template.queryForList(
|
||||
"select * from persistent_logins where username = 'joeuser'");
|
||||
|
||||
assertThat(results).isEmpty();
|
||||
}
|
||||
@@ -157,12 +175,13 @@ public class JdbcTokenRepositoryImplTests {
|
||||
@Test
|
||||
public void updatingTokenModifiesTokenValueAndLastUsed() {
|
||||
Timestamp ts = new Timestamp(System.currentTimeMillis() - 1);
|
||||
template.execute("insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries', 'joeuser', 'atoken', '" + ts.toString() + "')");
|
||||
template.execute(
|
||||
"insert into persistent_logins (series, username, token, last_used) values "
|
||||
+ "('joesseries', 'joeuser', 'atoken', '" + ts.toString() + "')");
|
||||
repo.updateToken("joesseries", "newtoken", new Date());
|
||||
|
||||
Map<String, Object> results = template
|
||||
.queryForMap("select * from persistent_logins where series = 'joesseries'");
|
||||
Map<String, Object> results = template.queryForMap(
|
||||
"select * from persistent_logins where series = 'joesseries'");
|
||||
|
||||
assertThat(results.get("username")).isEqualTo("joeuser");
|
||||
assertThat(results.get("series")).isEqualTo("joesseries");
|
||||
@@ -179,7 +198,8 @@ public class JdbcTokenRepositoryImplTests {
|
||||
repo.setCreateTableOnStartup(true);
|
||||
repo.initDao();
|
||||
|
||||
template.queryForList("select username,series,token,last_used from persistent_logins");
|
||||
template.queryForList(
|
||||
"select username,series,token,last_used from persistent_logins");
|
||||
}
|
||||
|
||||
// SEC-2879
|
||||
|
||||
@@ -15,19 +15,20 @@
|
||||
|
||||
package org.springframework.security.web.authentication.rememberme;
|
||||
|
||||
import org.springframework.security.web.authentication.NullRememberMeServices;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.web.authentication.NullRememberMeServices;
|
||||
|
||||
/**
|
||||
* Tests {@link org.springframework.security.web.authentication.NullRememberMeServices}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class NullRememberMeServicesTests extends TestCase {
|
||||
public class NullRememberMeServicesTests {
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void testAlwaysReturnsNull() {
|
||||
NullRememberMeServices services = new NullRememberMeServices();
|
||||
assertThat(services.autoLogin(null, null)).isNull();
|
||||
|
||||
@@ -307,8 +307,8 @@ public class TokenBasedRememberMeServicesTests {
|
||||
assertThat(cookie).isNotNull();
|
||||
assertThat(cookie.getMaxAge()).isEqualTo(services.getTokenValiditySeconds());
|
||||
assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue();
|
||||
assertThat(new Date().isTrue().before(new Date(
|
||||
determineExpiryTimeFromBased64EncodedToken(cookie.getValue()))));
|
||||
assertThat(new Date().before(new Date(
|
||||
determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -324,8 +324,8 @@ public class TokenBasedRememberMeServicesTests {
|
||||
assertThat(cookie).isNotNull();
|
||||
assertThat(cookie.getMaxAge()).isEqualTo(services.getTokenValiditySeconds());
|
||||
assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue();
|
||||
assertThat(new Date().isTrue().before(new Date(
|
||||
determineExpiryTimeFromBased64EncodedToken(cookie.getValue()))));
|
||||
assertThat(new Date().before(new Date(
|
||||
determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue();
|
||||
}
|
||||
|
||||
// SEC-933
|
||||
@@ -351,8 +351,8 @@ public class TokenBasedRememberMeServicesTests {
|
||||
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(cookie).isNotNull();
|
||||
// Check the expiry time is within 50ms of two weeks from current time
|
||||
assertThat(determineExpiryTimeFromBased64EncodedToken(cookie.getValue()).isTrue()
|
||||
- System.currentTimeMillis() > TWO_WEEKS_S - 50);
|
||||
assertThat(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())
|
||||
- System.currentTimeMillis() > TWO_WEEKS_S - 50).isTrue();
|
||||
assertThat(cookie.getMaxAge()).isEqualTo(-1);
|
||||
assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue();
|
||||
}
|
||||
|
||||
@@ -13,9 +13,10 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.authentication.session;
|
||||
|
||||
import static junit.framework.Assert.fail;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -38,14 +39,19 @@ import org.springframework.security.core.Authentication;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CompositeSessionAuthenticationStrategyTests {
|
||||
|
||||
@Mock
|
||||
private SessionAuthenticationStrategy strategy1;
|
||||
|
||||
@Mock
|
||||
private SessionAuthenticationStrategy strategy2;
|
||||
|
||||
@Mock
|
||||
private Authentication authentication;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
|
||||
@@ -78,8 +84,8 @@ public class CompositeSessionAuthenticationStrategyTests {
|
||||
|
||||
@Test
|
||||
public void delegateShortCircuits() {
|
||||
doThrow(new SessionAuthenticationException("oops")).when(strategy1)
|
||||
.onAuthentication(authentication, request, response);
|
||||
doThrow(new SessionAuthenticationException("oops")).when(
|
||||
strategy1).onAuthentication(authentication, request, response);
|
||||
|
||||
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
|
||||
Arrays.asList(strategy1, strategy2));
|
||||
|
||||
@@ -193,8 +193,7 @@ public class SwitchUserFilterTests {
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("/mywebapp/switchfailed");
|
||||
assertThat("/switchfailed").isEqualTo(
|
||||
FieldUtils.getFieldValue(filter, "switchFailureUrl"));
|
||||
assertThat(FieldUtils.getFieldValue(filter, "switchFailureUrl")).isEqualTo("/switchfailed");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
@@ -403,8 +402,8 @@ public class SwitchUserFilterTests {
|
||||
Authentication result = filter.attemptSwitchUser(request);
|
||||
assertThat(result != null).isTrue();
|
||||
assertThat(result.getAuthorities()).hasSize(2);
|
||||
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities()).contains(
|
||||
"ROLE_NEW"));
|
||||
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains(
|
||||
"ROLE_NEW");
|
||||
}
|
||||
|
||||
// SEC-1763
|
||||
|
||||
@@ -15,10 +15,12 @@
|
||||
|
||||
package org.springframework.security.web.authentication.www;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.springframework.security.authentication.DisabledException;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
@@ -27,29 +29,9 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class BasicAuthenticationEntryPointTests extends TestCase {
|
||||
// ~ Constructors
|
||||
// ===================================================================================================
|
||||
|
||||
public BasicAuthenticationEntryPointTests() {
|
||||
super();
|
||||
}
|
||||
|
||||
public BasicAuthenticationEntryPointTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public static void main(String[] args) {
|
||||
junit.textui.TestRunner.run(BasicAuthenticationEntryPointTests.class);
|
||||
}
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
public class BasicAuthenticationEntryPointTests {
|
||||
|
||||
@Test
|
||||
public void testDetectsMissingRealmName() throws Exception {
|
||||
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
|
||||
|
||||
@@ -61,13 +43,15 @@ public class BasicAuthenticationEntryPointTests extends TestCase {
|
||||
assertThat(expected.getMessage()).isEqualTo("realmName must be specified");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
|
||||
ep.setRealmName("realm");
|
||||
assertThat(ep.getRealmName()).isEqualTo("realm");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
|
||||
|
||||
|
||||
@@ -15,82 +15,90 @@
|
||||
|
||||
package org.springframework.security.web.authentication.www;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Tests {@link org.springframework.security.util.StringSplitUtils}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class DigestAuthUtilsTests extends TestCase {
|
||||
public class DigestAuthUtilsTests {
|
||||
// ~ Constructors
|
||||
// ===================================================================================================
|
||||
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void testSplitEachArrayElementAndCreateMapNormalOperation() {
|
||||
// note it ignores malformed entries (ie those without an equals sign)
|
||||
String unsplit = "username=\"rod\", invalidEntryThatHasNoEqualsSign, realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\"";
|
||||
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit);
|
||||
Map<String, String> headerMap = DigestAuthUtils
|
||||
.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
|
||||
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(
|
||||
headerEntries, "=", "\"");
|
||||
|
||||
assertThat(headerMap.get("username")).isEqualTo("rod");
|
||||
assertThat(headerMap.get("realm")).isEqualTo("Contacts Realm");
|
||||
assertEquals("MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==",
|
||||
headerMap.get("nonce"));
|
||||
assertEquals(
|
||||
"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4",
|
||||
headerMap.get("uri"));
|
||||
assertThat(headerMap.get("response")).isEqualTo("38644211cf9ac3da63ab639807e2baff");
|
||||
assertThat(headerMap.get("nonce")).isEqualTo(
|
||||
"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==");
|
||||
assertThat(headerMap.get("uri")).isEqualTo(
|
||||
"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4");
|
||||
assertThat(headerMap.get("response")).isEqualTo(
|
||||
"38644211cf9ac3da63ab639807e2baff");
|
||||
assertThat(headerMap.get("qop")).isEqualTo("auth");
|
||||
assertThat(headerMap.get("nc")).isEqualTo("00000004");
|
||||
assertThat(headerMap.get("cnonce")).isEqualTo("2b8d329a8571b99a");
|
||||
assertThat(headerMap).hasSize(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSplitEachArrayElementAndCreateMapRespectsInstructionNotToRemoveCharacters() {
|
||||
String unsplit = "username=\"rod\", realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\"";
|
||||
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit);
|
||||
Map<String, String> headerMap = DigestAuthUtils
|
||||
.splitEachArrayElementAndCreateMap(headerEntries, "=", null);
|
||||
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(
|
||||
headerEntries, "=", null);
|
||||
|
||||
assertThat(headerMap.get("username")).isEqualTo("\"rod\"");
|
||||
assertThat(headerMap.get("realm")).isEqualTo("\"Contacts Realm\"");
|
||||
assertEquals(
|
||||
"\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"",
|
||||
headerMap.get("nonce"));
|
||||
assertEquals(
|
||||
"\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"",
|
||||
headerMap.get("uri"));
|
||||
assertThat(headerMap.get("response")).isEqualTo("\"38644211cf9ac3da63ab639807e2baff\"");
|
||||
assertThat(headerMap.get("nonce")).isEqualTo(
|
||||
"\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"");
|
||||
assertThat(headerMap.get("uri")).isEqualTo(
|
||||
"\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"");
|
||||
assertThat(headerMap.get("response")).isEqualTo(
|
||||
"\"38644211cf9ac3da63ab639807e2baff\"");
|
||||
assertThat(headerMap.get("qop")).isEqualTo("auth");
|
||||
assertThat(headerMap.get("nc")).isEqualTo("00000004");
|
||||
assertThat(headerMap.get("cnonce")).isEqualTo("\"2b8d329a8571b99a\"");
|
||||
assertThat(headerMap).hasSize(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSplitEachArrayElementAndCreateMapReturnsNullIfArrayEmptyOrNull() {
|
||||
assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(null, "=", "\"")).isNull();
|
||||
assertNull(DigestAuthUtils.splitEachArrayElementAndCreateMap(new String[] {},
|
||||
"=", "\""));
|
||||
assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(null, "=",
|
||||
"\"")).isNull();
|
||||
assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(new String[] {}, "=",
|
||||
"\"")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSplitNormalOperation() {
|
||||
String unsplit = "username=\"rod==\"";
|
||||
assertThat("=")[0]).as("username").isEqualTo(DigestAuthUtils.split(unsplit);
|
||||
assertThat("=")[1]).as("\"rod==\"").isEqualTo(DigestAuthUtils.split(unsplit); // should not
|
||||
// remove
|
||||
// quotes or
|
||||
// extra
|
||||
// equals
|
||||
assertThat(DigestAuthUtils.split(unsplit, "=")[0]).isEqualTo("username");
|
||||
assertThat(DigestAuthUtils.split(unsplit, "=")[1]).isEqualTo("\"rod==\"");// should
|
||||
// not
|
||||
// remove
|
||||
// quotes
|
||||
// or
|
||||
// extra
|
||||
// equals
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSplitRejectsNullsAndIncorrectLengthStrings() {
|
||||
try {
|
||||
DigestAuthUtils.split(null, "="); // null
|
||||
@@ -133,12 +141,13 @@ public class DigestAuthUtilsTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSplitWorksWithDifferentDelimiters() {
|
||||
assertThat("/").length).isEqualTo(2, DigestAuthUtils.split("18/rod");
|
||||
assertThat(DigestAuthUtils.split("18/rod", "/").length).isEqualTo(2);
|
||||
assertThat(DigestAuthUtils.split("18/rod", "!")).isNull();
|
||||
|
||||
// only guarantees to split at FIRST delimiter, not EACH delimiter
|
||||
assertThat("|").length).isEqualTo(2, DigestAuthUtils.split("18|rod|foo|bar");
|
||||
assertThat(DigestAuthUtils.split("18|rod|foo|bar", "|").length).isEqualTo(2);
|
||||
}
|
||||
|
||||
public void testAuthorizationHeaderWithCommasIsSplitCorrectly() {
|
||||
|
||||
@@ -15,12 +15,13 @@
|
||||
|
||||
package org.springframework.security.web.authentication.www;
|
||||
|
||||
import java.util.Map;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.authentication.DisabledException;
|
||||
@@ -31,7 +32,7 @@ import org.springframework.util.StringUtils;
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class DigestAuthenticationEntryPointTests extends TestCase {
|
||||
public class DigestAuthenticationEntryPointTests {
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@@ -49,6 +50,7 @@ public class DigestAuthenticationEntryPointTests extends TestCase {
|
||||
assertThat(nonceTokens[1]).isEqualTo(expectedNonceSignature);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectsMissingKey() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setRealmName("realm");
|
||||
@@ -61,7 +63,8 @@ public class DigestAuthenticationEntryPointTests extends TestCase {
|
||||
assertThat(expected.getMessage()).isEqualTo("key must be specified");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testDetectsMissingRealmName() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setKey("dcdc");
|
||||
@@ -75,7 +78,8 @@ public class DigestAuthenticationEntryPointTests extends TestCase {
|
||||
assertThat(expected.getMessage()).isEqualTo("realmName must be specified");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
assertThat(ep.getNonceValiditySeconds()).isEqualTo(300); // 5 mins default
|
||||
@@ -86,7 +90,8 @@ public class DigestAuthenticationEntryPointTests extends TestCase {
|
||||
ep.setNonceValiditySeconds(12);
|
||||
assertThat(ep.getNonceValiditySeconds()).isEqualTo(12);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setRealmName("hello");
|
||||
@@ -103,8 +108,7 @@ public class DigestAuthenticationEntryPointTests extends TestCase {
|
||||
|
||||
// Check response is properly formed
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
assertEquals(true,
|
||||
response.getHeader("WWW-Authenticate").toString().startsWith("Digest "));
|
||||
assertThat(response.getHeader("WWW-Authenticate").toString()).startsWith("Digest ");
|
||||
|
||||
// Break up response header
|
||||
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
|
||||
@@ -118,7 +122,8 @@ public class DigestAuthenticationEntryPointTests extends TestCase {
|
||||
|
||||
checkNonceValid((String) headerMap.get("nonce"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testOperationIfDueToStaleNonce() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setRealmName("hello");
|
||||
@@ -135,8 +140,8 @@ public class DigestAuthenticationEntryPointTests extends TestCase {
|
||||
|
||||
// Check response is properly formed
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
assertThat(response.getHeader("WWW-Authenticate").toString().isTrue()
|
||||
.startsWith("Digest "));
|
||||
assertThat(response.getHeader("WWW-Authenticate").toString())
|
||||
.startsWith("Digest ");
|
||||
|
||||
// Break up response header
|
||||
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
|
||||
|
||||
@@ -15,13 +15,7 @@
|
||||
|
||||
package org.springframework.security.web.authentication.www;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -63,12 +57,19 @@ public class DigestAuthenticationFilterTests {
|
||||
// =====================================================================================
|
||||
|
||||
private static final String NC = "00000002";
|
||||
|
||||
private static final String CNONCE = "c822c727a648aba7";
|
||||
|
||||
private static final String REALM = "The Actual, Correct Realm Name";
|
||||
|
||||
private static final String KEY = "springsecurity";
|
||||
|
||||
private static final String QOP = "auth";
|
||||
|
||||
private static final String USERNAME = "rod,ok";
|
||||
|
||||
private static final String PASSWORD = "koala";
|
||||
|
||||
private static final String REQUEST_URI = "/some_file.html";
|
||||
|
||||
/**
|
||||
@@ -81,6 +82,7 @@ public class DigestAuthenticationFilterTests {
|
||||
|
||||
// private ApplicationContext ctx;
|
||||
private DigestAuthenticationFilter filter;
|
||||
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
// ~ Methods
|
||||
@@ -95,7 +97,7 @@ public class DigestAuthenticationFilterTests {
|
||||
|
||||
private MockHttpServletResponse executeFilterInContainerSimulator(Filter filter,
|
||||
final ServletRequest request, final boolean expectChainToProceed)
|
||||
throws ServletException, IOException {
|
||||
throws ServletException, IOException {
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
@@ -125,10 +127,11 @@ public class DigestAuthenticationFilterTests {
|
||||
|
||||
// Create User Details Service
|
||||
UserDetailsService uds = new UserDetailsService() {
|
||||
|
||||
public UserDetails loadUserByUsername(String username)
|
||||
throws UsernameNotFoundException {
|
||||
return new User("rod,ok", "koala", AuthorityUtils.createAuthorityList(
|
||||
"ROLE_ONE", "ROLE_TWO"));
|
||||
return new User("rod,ok", "koala",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -150,10 +153,8 @@ public class DigestAuthenticationFilterTests {
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
Thread.sleep(1000); // ensures token expired
|
||||
|
||||
@@ -165,8 +166,8 @@ public class DigestAuthenticationFilterTests {
|
||||
|
||||
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
|
||||
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
|
||||
Map<String, String> headerMap = DigestAuthUtils
|
||||
.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
|
||||
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(
|
||||
headerEntries, "=", "\"");
|
||||
assertThat(headerMap.get("stale")).isEqualTo("true");
|
||||
}
|
||||
|
||||
@@ -225,10 +226,8 @@ public class DigestAuthenticationFilterTests {
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
@@ -240,15 +239,13 @@ public class DigestAuthenticationFilterTests {
|
||||
@Test
|
||||
public void testNonceWithIncorrectSignatureForNumericFieldReturnsForbidden()
|
||||
throws Exception {
|
||||
String nonce = new String(Base64.encodeBase64("123456:incorrectStringPassword"
|
||||
.getBytes()));
|
||||
String nonce = new String(
|
||||
Base64.encodeBase64("123456:incorrectStringPassword".getBytes()));
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
@@ -259,15 +256,13 @@ public class DigestAuthenticationFilterTests {
|
||||
|
||||
@Test
|
||||
public void testNonceWithNonNumericFirstElementReturnsForbidden() throws Exception {
|
||||
String nonce = new String(Base64.encodeBase64("hello:ignoredSecondElement"
|
||||
.getBytes()));
|
||||
String nonce = new String(
|
||||
Base64.encodeBase64("hello:ignoredSecondElement".getBytes()));
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
@@ -279,15 +274,13 @@ public class DigestAuthenticationFilterTests {
|
||||
@Test
|
||||
public void testNonceWithoutTwoColonSeparatedElementsReturnsForbidden()
|
||||
throws Exception {
|
||||
String nonce = new String(Base64.encodeBase64("a base 64 string without a colon"
|
||||
.getBytes()));
|
||||
String nonce = new String(
|
||||
Base64.encodeBase64("a base 64 string without a colon".getBytes()));
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
@@ -298,21 +291,20 @@ public class DigestAuthenticationFilterTests {
|
||||
|
||||
@Test
|
||||
public void testNormalOperationWhenPasswordIsAlreadyEncoded() throws Exception {
|
||||
String encodedPassword = DigestAuthUtils.encodePasswordInA1Format(USERNAME,
|
||||
REALM, PASSWORD);
|
||||
String encodedPassword = DigestAuthUtils.encodePasswordInA1Format(USERNAME, REALM,
|
||||
PASSWORD);
|
||||
String responseDigest = DigestAuthUtils.generateDigest(true, USERNAME, REALM,
|
||||
encodedPassword, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(((UserDetails) SecurityContextHolder.getContext().isEqualTo(USERNAME)
|
||||
.getAuthentication().getPrincipal()).getUsername());
|
||||
assertThat(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()).isEqualTo(
|
||||
USERNAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -320,18 +312,17 @@ public class DigestAuthenticationFilterTests {
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(((UserDetails) SecurityContextHolder.getContext().isEqualTo(USERNAME)
|
||||
.getAuthentication().getPrincipal()).getUsername());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().isFalse()
|
||||
.isAuthenticated());
|
||||
assertThat(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()).isEqualTo(
|
||||
USERNAME);
|
||||
assertThat(
|
||||
SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -340,21 +331,21 @@ public class DigestAuthenticationFilterTests {
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
filter.setCreateAuthenticatedToken(true);
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(((UserDetails) SecurityContextHolder.getContext().isEqualTo(USERNAME)
|
||||
.getAuthentication().getPrincipal()).getUsername());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().isTrue()
|
||||
.isAuthenticated());
|
||||
assertThat("ROLE_TWO").isEqualTo(AuthorityUtils.createAuthorityList("ROLE_ONE"),
|
||||
SecurityContextHolder.getContext().getAuthentication().getAuthorities());
|
||||
assertThat(
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()).isEqualTo(
|
||||
USERNAME);
|
||||
assertThat(
|
||||
SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isTrue();
|
||||
assertThat(
|
||||
SecurityContextHolder.getContext().getAuthentication().getAuthorities()).isEqualTo(
|
||||
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -386,10 +377,8 @@ public class DigestAuthenticationFilterTests {
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
@@ -400,10 +389,8 @@ public class DigestAuthenticationFilterTests {
|
||||
"WRONG_PASSWORD", "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
|
||||
|
||||
request = new MockHttpServletRequest();
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
@@ -420,10 +407,8 @@ public class DigestAuthenticationFilterTests {
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, "DIFFERENT_CNONCE");
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, cnonce));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
NONCE, REQUEST_URI, responseDigest, QOP, NC, cnonce));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
@@ -438,10 +423,8 @@ public class DigestAuthenticationFilterTests {
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
password, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
@@ -456,10 +439,8 @@ public class DigestAuthenticationFilterTests {
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, realm,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, realm, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, realm,
|
||||
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
@@ -473,10 +454,8 @@ public class DigestAuthenticationFilterTests {
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, "NOT_A_KNOWN_USER",
|
||||
REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
@@ -489,7 +468,8 @@ public class DigestAuthenticationFilterTests {
|
||||
@Test
|
||||
public void authenticationCreatesEmptyContext() throws Exception {
|
||||
SecurityContext existingContext = SecurityContextHolder.createEmptyContext();
|
||||
TestingAuthenticationToken existingAuthentication = new TestingAuthenticationToken("existingauthenitcated", "pass", "ROLE_USER");
|
||||
TestingAuthenticationToken existingAuthentication = new TestingAuthenticationToken(
|
||||
"existingauthenitcated", "pass", "ROLE_USER");
|
||||
existingContext.setAuthentication(existingAuthentication);
|
||||
|
||||
SecurityContextHolder.setContext(existingContext);
|
||||
@@ -497,10 +477,8 @@ public class DigestAuthenticationFilterTests {
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
|
||||
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
filter.setCreateAuthenticatedToken(true);
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
@@ -87,9 +87,8 @@ public class ConcurrentSessionFilterTests {
|
||||
filter.doFilter(request, response, fc);
|
||||
verifyZeroInteractions(fc);
|
||||
|
||||
assertEquals(
|
||||
"This session has been expired (possibly due to multiple concurrent logins being "
|
||||
+ "attempted as the same user).", response.getContentAsString());
|
||||
assertThat(response.getContentAsString()).isEqualTo("This session has been expired (possibly due to multiple concurrent logins being "
|
||||
+ "attempted as the same user).");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
@@ -126,7 +125,6 @@ public class ConcurrentSessionFilterTests {
|
||||
filter.doFilter(request, response, fc);
|
||||
|
||||
verify(fc).doFilter(request, response);
|
||||
assertThat(registry.getSessionInformation(session.getId()).getLastRequest().isTrue()
|
||||
.after(lastRequest));
|
||||
assertThat(registry.getSessionInformation(session.getId()).getLastRequest().after(lastRequest)).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,14 +10,10 @@
|
||||
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.context;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Matchers.anyBoolean;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.reset;
|
||||
@@ -29,7 +25,11 @@ import static org.springframework.security.web.context.HttpSessionSecurityContex
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.http.*;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletRequestWrapper;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpServletResponseWrapper;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
@@ -53,6 +53,7 @@ import org.springframework.util.ClassUtils;
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest({ ClassUtils.class })
|
||||
public class HttpSessionSecurityContextRepositoryTests {
|
||||
|
||||
private final TestingAuthenticationToken testToken = new TestingAuthenticationToken(
|
||||
"someone", "passwd", "ROLE_A");
|
||||
|
||||
@@ -214,8 +215,9 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
context.setAuthentication(testToken);
|
||||
repo.saveContext(context, holder.getRequest(), holder.getResponse());
|
||||
assertThat(request.getSession(false)).isNotNull();
|
||||
assertEquals(context,
|
||||
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
|
||||
assertThat(
|
||||
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(
|
||||
context);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -229,15 +231,15 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().sendRedirect("/doesntmatter");
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue()
|
||||
.isContextSaved());
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
assertThat(
|
||||
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -251,15 +253,16 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().sendError(404);
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue()
|
||||
.isContextSaved());
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
|
||||
assertThat(
|
||||
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
}
|
||||
|
||||
// SEC-2005
|
||||
@@ -274,15 +277,15 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().flushBuffer();
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue()
|
||||
.isContextSaved());
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
assertThat(
|
||||
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
}
|
||||
|
||||
// SEC-2005
|
||||
@@ -297,15 +300,15 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getWriter().flush();
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue()
|
||||
.isContextSaved());
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
assertThat(
|
||||
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
}
|
||||
|
||||
// SEC-2005
|
||||
@@ -320,15 +323,15 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getWriter().close();
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue()
|
||||
.isContextSaved());
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
assertThat(
|
||||
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
}
|
||||
|
||||
// SEC-2005
|
||||
@@ -343,15 +346,15 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getOutputStream().flush();
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue()
|
||||
.isContextSaved());
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
assertThat(
|
||||
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
}
|
||||
|
||||
// SEC-2005
|
||||
@@ -366,15 +369,15 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getOutputStream().close();
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isTrue()
|
||||
.isContextSaved());
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
assertThat(
|
||||
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertThat(request.getSession().isEqualTo(SecurityContextHolder.getContext())
|
||||
.getAttribute("imTheContext"));
|
||||
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
|
||||
SecurityContextHolder.getContext());
|
||||
}
|
||||
|
||||
// SEC-SEC-2055
|
||||
@@ -438,8 +441,8 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new AnonymousAuthenticationToken("key", "anon", AuthorityUtils
|
||||
.createAuthorityList("ANON")));
|
||||
new AnonymousAuthenticationToken("key", "anon",
|
||||
AuthorityUtils.createAuthorityList("ANON")));
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
assertThat(request.getSession(false)).isNull();
|
||||
@@ -447,7 +450,8 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
|
||||
// SEC-1587
|
||||
@Test
|
||||
public void contextIsRemovedFromSessionIfCurrentContextIsAnonymous() throws Exception {
|
||||
public void contextIsRemovedFromSessionIfCurrentContextIsAnonymous()
|
||||
throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
|
||||
@@ -460,7 +464,8 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
new AnonymousAuthenticationToken("x", "x", testToken.getAuthorities()));
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
|
||||
assertThat(
|
||||
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -493,11 +498,11 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
ctxInSession.setAuthentication(testToken);
|
||||
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new AnonymousAuthenticationToken("x", "x", AuthorityUtils
|
||||
.createAuthorityList("ROLE_ANONYMOUS")));
|
||||
new AnonymousAuthenticationToken("x", "x",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
assertSame(ctxInSession,
|
||||
assertThat(ctxInSession).isSameAs(
|
||||
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
|
||||
}
|
||||
|
||||
@@ -510,13 +515,15 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
ctxInSession.setAuthentication(testToken);
|
||||
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
|
||||
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
new MockHttpServletResponse());
|
||||
repo.loadContext(holder);
|
||||
|
||||
ctxInSession.setAuthentication(null);
|
||||
repo.saveContext(ctxInSession, holder.getRequest(), holder.getResponse());
|
||||
|
||||
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
|
||||
assertThat(
|
||||
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -527,6 +534,7 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final String sessionId = ";jsessionid=id";
|
||||
MockHttpServletResponse response = new MockHttpServletResponse() {
|
||||
|
||||
@Override
|
||||
public String encodeRedirectUrl(String url) {
|
||||
return url + sessionId;
|
||||
@@ -551,8 +559,10 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
response);
|
||||
repo.loadContext(holder);
|
||||
String url = "/aUrl";
|
||||
assertThat(holder.getResponse().encodeRedirectUrl(url)).isEqualTo(url + sessionId);
|
||||
assertThat(holder.getResponse().encodeRedirectURL(url)).isEqualTo(url + sessionId);
|
||||
assertThat(holder.getResponse().encodeRedirectUrl(url)).isEqualTo(
|
||||
url + sessionId);
|
||||
assertThat(holder.getResponse().encodeRedirectURL(url)).isEqualTo(
|
||||
url + sessionId);
|
||||
assertThat(holder.getResponse().encodeUrl(url)).isEqualTo(url + sessionId);
|
||||
assertThat(holder.getResponse().encodeURL(url)).isEqualTo(url + sessionId);
|
||||
repo.setDisableUrlRewriting(true);
|
||||
@@ -573,7 +583,8 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
new MockHttpServletResponse());
|
||||
repo.loadContext(holder);
|
||||
AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class);
|
||||
AuthenticationTrustResolver trustResolver = mock(
|
||||
AuthenticationTrustResolver.class);
|
||||
repo.setTrustResolver(trustResolver);
|
||||
|
||||
repo.saveContext(contextToSave, holder.getRequest(), holder.getResponse());
|
||||
@@ -604,8 +615,9 @@ public class HttpSessionSecurityContextRepositoryTests {
|
||||
new HttpServletResponseWrapper(holder.getResponse()));
|
||||
|
||||
assertThat(request.getSession(false)).isNotNull();
|
||||
assertEquals(context,
|
||||
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
|
||||
assertThat(
|
||||
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(
|
||||
context);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
|
||||
@@ -52,7 +52,7 @@ public class SecurityContextPersistenceFilterTests {
|
||||
any(ServletResponse.class));
|
||||
try {
|
||||
filter.doFilter(request, response, chain);
|
||||
fail();
|
||||
fail("IOException should have been thrown");
|
||||
}
|
||||
catch (IOException expected) {
|
||||
}
|
||||
@@ -80,8 +80,7 @@ public class SecurityContextPersistenceFilterTests {
|
||||
final FilterChain chain = new FilterChain() {
|
||||
public void doFilter(ServletRequest request, ServletResponse response)
|
||||
throws IOException, ServletException {
|
||||
assertThat(SecurityContextHolder.getContext().isEqualTo(beforeAuth)
|
||||
.getAuthentication());
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(beforeAuth);
|
||||
// Change the context here
|
||||
SecurityContextHolder.setContext(scExpectedAfter);
|
||||
}
|
||||
|
||||
@@ -21,20 +21,20 @@ public class FirewalledResponseTests {
|
||||
|
||||
try {
|
||||
fwResponse.sendRedirect("/theURL\r\nsomething");
|
||||
fail();
|
||||
fail("IllegalArgumentException should have thrown");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
try {
|
||||
fwResponse.sendRedirect("/theURL\rsomething");
|
||||
fail();
|
||||
fail("IllegalArgumentException should have thrown");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
fwResponse.sendRedirect("/theURL\nsomething");
|
||||
fail();
|
||||
fail("IllegalArgumentException should have thrown");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
|
||||
package org.springframework.security.web.header.writers.frameoptions;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.regex.PatternSyntaxException;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.security.web.header.writers.frameoptions.RegExpAllowFromStrategy;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -34,15 +33,15 @@ public class RegExpAllowFromStrategyTests {
|
||||
|
||||
request.setParameter("from", "http://abc.test.com");
|
||||
String result1 = strategy.getAllowFromValue(request);
|
||||
assertThat(result1, is("http://abc.test.com"));
|
||||
assertThat(result1).isEqualTo("http://abc.test.com");
|
||||
|
||||
request.setParameter("from", "http://foo.test.com");
|
||||
String result2 = strategy.getAllowFromValue(request);
|
||||
assertThat(result2, is("http://foo.test.com"));
|
||||
assertThat(result2).isEqualTo("http://foo.test.com");
|
||||
|
||||
request.setParameter("from", "http://test.foobar.com");
|
||||
String result3 = strategy.getAllowFromValue(request);
|
||||
assertThat(result3, is("DENY"));
|
||||
assertThat(result3).isEqualTo("DENY");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -51,6 +50,6 @@ public class RegExpAllowFromStrategyTests {
|
||||
"^http://([a-z0-9]*?\\.)test\\.com");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
String result1 = strategy.getAllowFromValue(request);
|
||||
assertThat(result1, is("DENY"));
|
||||
assertThat(result1).isEqualTo("DENY");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,11 +13,10 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.jaasapi;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.AccessController;
|
||||
@@ -51,7 +50,6 @@ import org.springframework.security.authentication.jaas.TestLoginModule;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.jaasapi.JaasApiIntegrationFilter;
|
||||
|
||||
/**
|
||||
* Tests the JaasApiIntegrationFilter.
|
||||
@@ -59,14 +57,21 @@ import org.springframework.security.web.jaasapi.JaasApiIntegrationFilter;
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class JaasApiIntegrationFilterTests {
|
||||
|
||||
// ~ Instance fields
|
||||
// ================================================================================================
|
||||
private JaasApiIntegrationFilter filter;
|
||||
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
private Authentication token;
|
||||
|
||||
private Subject authenticatedSubject;
|
||||
|
||||
private Configuration testConfiguration;
|
||||
|
||||
private CallbackHandler callbackHandler;
|
||||
|
||||
// ~ Methods
|
||||
@@ -80,6 +85,7 @@ public class JaasApiIntegrationFilterTests {
|
||||
|
||||
authenticatedSubject = new Subject();
|
||||
authenticatedSubject.getPrincipals().add(new Principal() {
|
||||
|
||||
public String getName() {
|
||||
return "principal";
|
||||
}
|
||||
@@ -87,15 +93,16 @@ public class JaasApiIntegrationFilterTests {
|
||||
authenticatedSubject.getPrivateCredentials().add("password");
|
||||
authenticatedSubject.getPublicCredentials().add("username");
|
||||
callbackHandler = new CallbackHandler() {
|
||||
public void handle(Callback[] callbacks) throws IOException,
|
||||
UnsupportedCallbackException {
|
||||
|
||||
public void handle(Callback[] callbacks)
|
||||
throws IOException, UnsupportedCallbackException {
|
||||
for (Callback callback : callbacks) {
|
||||
if (callback instanceof NameCallback) {
|
||||
((NameCallback) callback).setName("user");
|
||||
}
|
||||
else if (callback instanceof PasswordCallback) {
|
||||
((PasswordCallback) callback).setPassword("password"
|
||||
.toCharArray());
|
||||
((PasswordCallback) callback).setPassword(
|
||||
"password".toCharArray());
|
||||
}
|
||||
else if (callback instanceof TextInputCallback) {
|
||||
// ignore
|
||||
@@ -108,6 +115,7 @@ public class JaasApiIntegrationFilterTests {
|
||||
}
|
||||
};
|
||||
testConfiguration = new Configuration() {
|
||||
|
||||
public void refresh() {
|
||||
}
|
||||
|
||||
@@ -117,8 +125,8 @@ public class JaasApiIntegrationFilterTests {
|
||||
new HashMap<String, String>()) };
|
||||
}
|
||||
};
|
||||
LoginContext ctx = new LoginContext("SubjectDoAsFilterTest",
|
||||
authenticatedSubject, callbackHandler, testConfiguration);
|
||||
LoginContext ctx = new LoginContext("SubjectDoAsFilterTest", authenticatedSubject,
|
||||
callbackHandler, testConfiguration);
|
||||
ctx.login();
|
||||
token = new JaasAuthenticationToken("username", "password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx);
|
||||
@@ -206,11 +214,12 @@ public class JaasApiIntegrationFilterTests {
|
||||
|
||||
private void assertJaasSubjectEquals(final Subject expectedValue) throws Exception {
|
||||
MockFilterChain chain = new MockFilterChain() {
|
||||
|
||||
public void doFilter(ServletRequest request, ServletResponse response)
|
||||
throws IOException, ServletException {
|
||||
// See if the subject was updated
|
||||
Subject currentSubject = Subject
|
||||
.getSubject(AccessController.getContext());
|
||||
Subject currentSubject = Subject.getSubject(
|
||||
AccessController.getContext());
|
||||
assertThat(currentSubject).isEqualTo(expectedValue);
|
||||
|
||||
// run so we know the chain was executed
|
||||
@@ -223,6 +232,7 @@ public class JaasApiIntegrationFilterTests {
|
||||
}
|
||||
|
||||
private void assertNullSubject(Subject subject) {
|
||||
assertThat("Subject is expected to be null, but is not. Got " + subject, subject).isNull();
|
||||
assertThat(subject).withFailMessage(
|
||||
"Subject is expected to be null, but is not. Got " + subject).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
|
||||
package org.springframework.security.web.savedrequest;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
@@ -30,11 +29,12 @@ public class HttpSessionRequestCacheTests {
|
||||
public void originalGetRequestDoesntMatchIncomingPost() {
|
||||
HttpSessionRequestCache cache = new HttpSessionRequestCache();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/destination");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/destination");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
cache.saveRequest(request, response);
|
||||
assertThat(request.getSession().isNotNull().getAttribute(
|
||||
HttpSessionRequestCache.SAVED_REQUEST));
|
||||
assertThat(request.getSession().getAttribute(
|
||||
HttpSessionRequestCache.SAVED_REQUEST)).isNotNull();
|
||||
assertThat(cache.getRequest(request, response)).isNotNull();
|
||||
|
||||
MockHttpServletRequest newRequest = new MockHttpServletRequest("POST",
|
||||
@@ -48,6 +48,7 @@ public class HttpSessionRequestCacheTests {
|
||||
public void requestMatcherDefinesCorrectSubsetOfCachedRequests() throws Exception {
|
||||
HttpSessionRequestCache cache = new HttpSessionRequestCache();
|
||||
cache.setRequestMatcher(new RequestMatcher() {
|
||||
|
||||
public boolean matches(HttpServletRequest request) {
|
||||
return request.getMethod().equals("GET");
|
||||
}
|
||||
@@ -58,8 +59,8 @@ public class HttpSessionRequestCacheTests {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
cache.saveRequest(request, response);
|
||||
assertThat(cache.getRequest(request, response)).isNull();
|
||||
assertThat(cache.getRequest(new MockHttpServletRequest().isNull(),
|
||||
new MockHttpServletResponse()));
|
||||
assertThat(cache.getRequest(new MockHttpServletRequest(),
|
||||
new MockHttpServletResponse())).isNull();
|
||||
assertThat(cache.getMatchingRequest(request, response)).isNull();
|
||||
}
|
||||
|
||||
@@ -74,10 +75,8 @@ public class HttpSessionRequestCacheTests {
|
||||
@Override
|
||||
public void saveRequest(HttpServletRequest request,
|
||||
HttpServletResponse response) {
|
||||
request.getSession().setAttribute(
|
||||
SAVED_REQUEST,
|
||||
new CustomSavedRequest(new DefaultSavedRequest(request,
|
||||
new PortResolverImpl())));
|
||||
request.getSession().setAttribute(SAVED_REQUEST, new CustomSavedRequest(
|
||||
new DefaultSavedRequest(request, new PortResolverImpl())));
|
||||
}
|
||||
|
||||
};
|
||||
@@ -89,6 +88,7 @@ public class HttpSessionRequestCacheTests {
|
||||
}
|
||||
|
||||
private static final class CustomSavedRequest implements SavedRequest {
|
||||
|
||||
private final SavedRequest delegate;
|
||||
|
||||
private CustomSavedRequest(SavedRequest delegate) {
|
||||
|
||||
@@ -18,11 +18,11 @@ public class RequestCacheAwareFilterTests {
|
||||
"/destination");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
cache.saveRequest(request, response);
|
||||
assertThat(request.getSession().isNotNull().getAttribute(
|
||||
HttpSessionRequestCache.SAVED_REQUEST));
|
||||
assertThat(request.getSession().getAttribute(
|
||||
HttpSessionRequestCache.SAVED_REQUEST)).isNotNull();
|
||||
|
||||
filter.doFilter(request, response, new MockFilterChain());
|
||||
assertThat(request.getSession().isNull().getAttribute(
|
||||
HttpSessionRequestCache.SAVED_REQUEST));
|
||||
assertThat(request.getSession().getAttribute(
|
||||
HttpSessionRequestCache.SAVED_REQUEST)).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
package org.springframework.security.web.savedrequest;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.web.savedrequest.SavedCookie;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class SavedCookieTests extends TestCase {
|
||||
public class SavedCookieTests {
|
||||
|
||||
Cookie cookie;
|
||||
SavedCookie savedCookie;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
cookie = new Cookie("name", "value");
|
||||
cookie.setComment("comment");
|
||||
cookie.setDomain("domain");
|
||||
@@ -24,34 +27,42 @@ public class SavedCookieTests extends TestCase {
|
||||
savedCookie = new SavedCookie(cookie);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetName() throws Exception {
|
||||
assertThat(savedCookie.getName()).isEqualTo(cookie.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetValue() throws Exception {
|
||||
assertThat(savedCookie.getValue()).isEqualTo(cookie.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetComment() throws Exception {
|
||||
assertThat(savedCookie.getComment()).isEqualTo(cookie.getComment());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDomain() throws Exception {
|
||||
assertThat(savedCookie.getDomain()).isEqualTo(cookie.getDomain());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetMaxAge() throws Exception {
|
||||
assertThat(savedCookie.getMaxAge()).isEqualTo(cookie.getMaxAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetPath() throws Exception {
|
||||
assertThat(savedCookie.getPath()).isEqualTo(cookie.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetVersion() throws Exception {
|
||||
assertThat(savedCookie.getVersion()).isEqualTo(cookie.getVersion());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCookie() throws Exception {
|
||||
Cookie other = savedCookie.getCookie();
|
||||
assertThat(other.getComment()).isEqualTo(cookie.getComment());
|
||||
@@ -64,6 +75,7 @@ public class SavedCookieTests extends TestCase {
|
||||
assertThat(other.getVersion()).isEqualTo(cookie.getVersion());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSerializable() throws Exception {
|
||||
assertThat(savedCookie instanceof Serializable).isTrue();
|
||||
}
|
||||
|
||||
@@ -117,8 +117,7 @@ public class SavedRequestAwareWrapperTests {
|
||||
|
||||
assertThat(wrapper.getParameterValues("action")).isEqualTo(new Object[] { "foo" });
|
||||
wrappedRequest.setParameter("action", "bar");
|
||||
assertArrayEquals(new Object[] { "bar", "foo" },
|
||||
wrapper.getParameterValues("action"));
|
||||
assertThat(wrapper.getParameterValues("action")).isEqualTo(new Object[] { "bar", "foo" });
|
||||
// Check map is consistent
|
||||
String[] valuesFromMap = (String[]) wrapper.getParameterMap().get("action");
|
||||
assertThat(valuesFromMap.length).isEqualTo(2);
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
|
||||
package org.springframework.security.web.servletapi;
|
||||
|
||||
import static junit.framework.Assert.fail;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Matchers.eq;
|
||||
@@ -37,8 +37,6 @@ import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
@@ -72,18 +70,25 @@ import org.springframework.util.ClassUtils;
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest(ClassUtils.class)
|
||||
public class SecurityContextHolderAwareRequestFilterTests {
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<HttpServletRequest> requestCaptor;
|
||||
|
||||
@Mock
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Mock
|
||||
private AuthenticationEntryPoint authenticationEntryPoint;
|
||||
|
||||
@Mock
|
||||
private LogoutHandler logoutHandler;
|
||||
|
||||
@Mock
|
||||
private FilterChain filterChain;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
|
||||
@@ -174,10 +179,8 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
||||
public void login() throws Exception {
|
||||
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user",
|
||||
"password", "ROLE_USER");
|
||||
when(
|
||||
authenticationManager
|
||||
.authenticate(any(UsernamePasswordAuthenticationToken.class)))
|
||||
.thenReturn(expectedAuth);
|
||||
when(authenticationManager.authenticate(
|
||||
any(UsernamePasswordAuthenticationToken.class))).thenReturn(expectedAuth);
|
||||
|
||||
wrappedRequest().login(expectedAuth.getName(),
|
||||
String.valueOf(expectedAuth.getCredentials()));
|
||||
@@ -193,10 +196,8 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
||||
public void loginWithExstingUser() throws Exception {
|
||||
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user",
|
||||
"password", "ROLE_USER");
|
||||
when(
|
||||
authenticationManager
|
||||
.authenticate(any(UsernamePasswordAuthenticationToken.class)))
|
||||
.thenReturn(
|
||||
when(authenticationManager.authenticate(
|
||||
any(UsernamePasswordAuthenticationToken.class))).thenReturn(
|
||||
new TestingAuthenticationToken("newuser", "not be found",
|
||||
"ROLE_USER"));
|
||||
SecurityContextHolder.getContext().setAuthentication(expectedAuth);
|
||||
@@ -217,14 +218,12 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
||||
@Test
|
||||
public void loginFail() throws Exception {
|
||||
AuthenticationException authException = new BadCredentialsException("Invalid");
|
||||
when(
|
||||
authenticationManager
|
||||
.authenticate(any(UsernamePasswordAuthenticationToken.class)))
|
||||
.thenThrow(authException);
|
||||
when(authenticationManager.authenticate(
|
||||
any(UsernamePasswordAuthenticationToken.class))).thenThrow(authException);
|
||||
|
||||
try {
|
||||
wrappedRequest().login("invalid", "credentials");
|
||||
Assert.fail("Expected Exception");
|
||||
fail("Expected Exception");
|
||||
}
|
||||
catch (ServletException success) {
|
||||
assertThat(success.getCause()).isEqualTo(authException);
|
||||
@@ -262,7 +261,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
||||
|
||||
try {
|
||||
wrappedRequest().login(username, password);
|
||||
Assert.fail("Expected Exception");
|
||||
fail("Expected Exception");
|
||||
}
|
||||
catch (ServletException success) {
|
||||
assertThat(success).isEqualTo(authException);
|
||||
@@ -309,6 +308,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
||||
AsyncContext asyncContext = mock(AsyncContext.class);
|
||||
when(request.getAsyncContext()).thenReturn(asyncContext);
|
||||
Runnable runnable = new Runnable() {
|
||||
|
||||
public void run() {
|
||||
}
|
||||
};
|
||||
@@ -317,12 +317,11 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
||||
|
||||
verifyZeroInteractions(authenticationManager, logoutHandler);
|
||||
verify(asyncContext).start(runnableCaptor.capture());
|
||||
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor
|
||||
.getValue();
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegateSecurityContext"))
|
||||
.isEqualTo(context);
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate"))
|
||||
.isEqualTo(runnable);
|
||||
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable,
|
||||
"delegateSecurityContext")).isEqualTo(context);
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate")).isEqualTo(
|
||||
runnable);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -336,6 +335,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
||||
AsyncContext asyncContext = mock(AsyncContext.class);
|
||||
when(request.startAsync()).thenReturn(asyncContext);
|
||||
Runnable runnable = new Runnable() {
|
||||
|
||||
public void run() {
|
||||
}
|
||||
};
|
||||
@@ -344,12 +344,11 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
||||
|
||||
verifyZeroInteractions(authenticationManager, logoutHandler);
|
||||
verify(asyncContext).start(runnableCaptor.capture());
|
||||
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor
|
||||
.getValue();
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegateSecurityContext"))
|
||||
.isEqualTo(context);
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate"))
|
||||
.isEqualTo(runnable);
|
||||
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable,
|
||||
"delegateSecurityContext")).isEqualTo(context);
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate")).isEqualTo(
|
||||
runnable);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -363,6 +362,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
||||
AsyncContext asyncContext = mock(AsyncContext.class);
|
||||
when(request.startAsync(request, response)).thenReturn(asyncContext);
|
||||
Runnable runnable = new Runnable() {
|
||||
|
||||
public void run() {
|
||||
}
|
||||
};
|
||||
@@ -371,22 +371,22 @@ public class SecurityContextHolderAwareRequestFilterTests {
|
||||
|
||||
verifyZeroInteractions(authenticationManager, logoutHandler);
|
||||
verify(asyncContext).start(runnableCaptor.capture());
|
||||
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor
|
||||
.getValue();
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegateSecurityContext"))
|
||||
.isEqualTo(context);
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate"))
|
||||
.isEqualTo(runnable);
|
||||
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable,
|
||||
"delegateSecurityContext")).isEqualTo(context);
|
||||
assertThat(WhiteboxImpl.getInternalState(wrappedRunnable, "delegate")).isEqualTo(
|
||||
runnable);
|
||||
}
|
||||
|
||||
// SEC-3047
|
||||
@Test
|
||||
public void updateRequestFactory() throws Exception {
|
||||
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("user",
|
||||
"password", "PREFIX_USER"));
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new TestingAuthenticationToken("user", "password", "PREFIX_USER"));
|
||||
filter.setRolePrefix("PREFIX_");
|
||||
|
||||
assertThat(wrappedRequest().isUserInRole("PREFIX_USER")).isTrue();;
|
||||
assertThat(wrappedRequest().isUserInRole("PREFIX_USER")).isTrue();
|
||||
;
|
||||
}
|
||||
|
||||
private HttpServletRequest wrappedRequest() throws Exception {
|
||||
|
||||
@@ -15,8 +15,10 @@
|
||||
|
||||
package org.springframework.security.web.servletapi;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
@@ -30,12 +32,14 @@ import org.springframework.security.web.servletapi.SecurityContextHolderAwareReq
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class SecurityContextHolderAwareRequestWrapperTests extends TestCase {
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
public class SecurityContextHolderAwareRequestWrapperTests {
|
||||
|
||||
@Before
|
||||
public void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCorrectOperationWithStringBasedPrincipal() throws Exception {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", "ROLE_FOO");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
@@ -52,6 +56,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase {
|
||||
assertThat(wrapper.getUserPrincipal()).isEqualTo(auth);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUseOfRolePrefixMeansItIsntNeededWhenCallngIsUserInRole() {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", "ROLE_FOO");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
@@ -65,6 +70,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase {
|
||||
assertThat(wrapper.isUserInRole("FOO")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCorrectOperationWithUserDetailsBasedPrincipal() throws Exception {
|
||||
Authentication auth = new TestingAuthenticationToken(new User("rodAsUserDetails",
|
||||
"koala", true, true, true, true, AuthorityUtils.NO_AUTHORITIES), "koala",
|
||||
@@ -85,6 +91,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase {
|
||||
assertThat(wrapper.getUserPrincipal()).isEqualTo(auth);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRoleIsntHeldIfAuthenticationIsNull() throws Exception {
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
|
||||
@@ -98,6 +105,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase {
|
||||
assertThat(wrapper.getUserPrincipal()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRolesArentHeldIfAuthenticationPrincipalIsNull() throws Exception {
|
||||
Authentication auth = new TestingAuthenticationToken(null, "koala", "ROLE_HELLO",
|
||||
"ROLE_FOOBAR");
|
||||
@@ -115,6 +123,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase {
|
||||
assertThat(wrapper.getUserPrincipal()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRolePrefix() {
|
||||
Authentication auth = new TestingAuthenticationToken("user", "koala", "ROLE_HELLO",
|
||||
"ROLE_FOOBAR");
|
||||
@@ -130,6 +139,7 @@ public class SecurityContextHolderAwareRequestWrapperTests extends TestCase {
|
||||
}
|
||||
|
||||
// SEC-3020
|
||||
@Test
|
||||
public void testRolePrefixNotAppliedIfRoleStartsWith() {
|
||||
Authentication auth = new TestingAuthenticationToken("user", "koala", "ROLE_HELLO",
|
||||
"ROLE_FOOBAR");
|
||||
|
||||
@@ -87,8 +87,8 @@ public class DefaultSessionAuthenticationStrategyTests {
|
||||
|
||||
assertThat(oldSessionId.equals(request.getSession().getId())).isFalse();
|
||||
assertThat(request.getSession().getAttribute("blah")).isNotNull();
|
||||
assertThat(request.getSession().isNotNull().getAttribute(
|
||||
"SPRING_SECURITY_SAVED_REQUEST_KEY"));
|
||||
assertThat(request.getSession().getAttribute(
|
||||
"SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull();
|
||||
|
||||
assertThat(eventArgumentCaptor.getValue()).isNotNull();
|
||||
assertThat(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent).isTrue();
|
||||
@@ -114,8 +114,8 @@ public class DefaultSessionAuthenticationStrategyTests {
|
||||
new MockHttpServletResponse());
|
||||
|
||||
assertThat(request.getSession().getAttribute("blah")).isNull();
|
||||
assertThat(request.getSession().isNotNull().getAttribute(
|
||||
"SPRING_SECURITY_SAVED_REQUEST_KEY"));
|
||||
assertThat(request.getSession().getAttribute(
|
||||
"SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull();
|
||||
}
|
||||
|
||||
// SEC-2002
|
||||
@@ -143,8 +143,8 @@ public class DefaultSessionAuthenticationStrategyTests {
|
||||
verify(eventPublisher).publishEvent(eventArgumentCaptor.capture());
|
||||
|
||||
assertThat(request.getSession().getAttribute("blah")).isNull();
|
||||
assertThat(request.getSession().isNotNull().getAttribute(
|
||||
"SPRING_SECURITY_SAVED_REQUEST_KEY"));
|
||||
assertThat(request.getSession().getAttribute(
|
||||
"SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull();
|
||||
|
||||
assertThat(eventArgumentCaptor.getValue()).isNotNull();
|
||||
assertThat(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent).isTrue();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
package org.springframework.security.web.session;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import java.util.List;
|
||||
@@ -18,7 +18,9 @@ import org.springframework.security.core.context.SecurityContextImpl;
|
||||
*
|
||||
*/
|
||||
public class HttpSessionDestroyedEventTests {
|
||||
|
||||
private MockHttpSession session;
|
||||
|
||||
private HttpSessionDestroyedEvent destroyedEvent;
|
||||
|
||||
@Before
|
||||
|
||||
@@ -12,8 +12,8 @@ public class TextEscapeUtilsTests {
|
||||
*/
|
||||
@Test
|
||||
public void charactersAreEscapedCorrectly() {
|
||||
assertEquals("& a<script>"'",
|
||||
TextEscapeUtils.escapeEntities("& a<script>\"'"));
|
||||
assertThat(TextEscapeUtils.escapeEntities("& a<script>\"'")).isEqualTo(
|
||||
"& a<script>"'");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
|
||||
package org.springframework.security.web.util;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
|
||||
import org.springframework.security.web.util.ThrowableAnalyzer;
|
||||
import org.springframework.security.web.util.ThrowableCauseExtractor;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Test cases for {@link ThrowableAnalyzer}.
|
||||
@@ -13,7 +15,7 @@ import junit.framework.TestCase;
|
||||
* @author Andreas Senft
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public class ThrowableAnalyzerTests extends TestCase {
|
||||
public class ThrowableAnalyzerTests {
|
||||
|
||||
/**
|
||||
* Exception for testing purposes. The cause is not retrievable by {@link #getCause()}
|
||||
@@ -37,8 +39,8 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
* <code>ThrowableCauseExtractor</code> for handling <code>NonStandardException</code>
|
||||
* instances.
|
||||
*/
|
||||
public static final class NonStandardExceptionCauseExtractor implements
|
||||
ThrowableCauseExtractor {
|
||||
public static final class NonStandardExceptionCauseExtractor
|
||||
implements ThrowableCauseExtractor {
|
||||
|
||||
public Throwable extractCause(Throwable throwable) {
|
||||
ThrowableAnalyzer.verifyThrowableHierarchy(throwable,
|
||||
@@ -65,12 +67,8 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
*/
|
||||
private ThrowableAnalyzer nonstandardAnalyzer;
|
||||
|
||||
/**
|
||||
* @see junit.framework.TestCase#setUp()
|
||||
*/
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
|
||||
// Set up test trace
|
||||
this.testTrace = new Throwable[7];
|
||||
@@ -87,6 +85,7 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
|
||||
// Set up nonstandard analyzer
|
||||
this.nonstandardAnalyzer = new ThrowableAnalyzer() {
|
||||
|
||||
/**
|
||||
* @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap()
|
||||
*/
|
||||
@@ -100,14 +99,7 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @see junit.framework.TestCase#tearDown()
|
||||
*/
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRegisterExtractorWithInvalidExtractor() {
|
||||
try {
|
||||
new ThrowableAnalyzer() {
|
||||
@@ -129,6 +121,7 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetRegisteredTypes() {
|
||||
|
||||
Class[] registeredTypes = this.nonstandardAnalyzer.getRegisteredTypes();
|
||||
@@ -140,13 +133,14 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
for (int j = 0; j < i; ++j) {
|
||||
Class prevClazz = registeredTypes[j];
|
||||
|
||||
assertFalse("Unexpected order of registered classes: " + prevClazz
|
||||
+ " is assignable from " + clazz,
|
||||
prevClazz.isAssignableFrom(clazz));
|
||||
assertThat(prevClazz.isAssignableFrom(clazz)).withFailMessage(
|
||||
"Unexpected order of registered classes: " + prevClazz
|
||||
+ " is assignable from " + clazz).isFalse();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetermineCauseChainWithNoExtractors() {
|
||||
ThrowableAnalyzer analyzer = new ThrowableAnalyzer() {
|
||||
|
||||
@@ -159,8 +153,8 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
}
|
||||
};
|
||||
|
||||
assertEquals("Unexpected number of registered types", 0,
|
||||
analyzer.getRegisteredTypes().length);
|
||||
assertThat(analyzer.getRegisteredTypes().length).withFailMessage(
|
||||
"Unexpected number of registered types").isEqualTo(0);
|
||||
|
||||
Throwable t = this.testTrace[0];
|
||||
Throwable[] chain = analyzer.determineCauseChain(t);
|
||||
@@ -169,11 +163,12 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
assertThat(chain[0]).as("Unexpected chain entry").isEqualTo(t);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetermineCauseChainWithDefaultExtractors() {
|
||||
ThrowableAnalyzer analyzer = this.standardAnalyzer;
|
||||
|
||||
assertEquals("Unexpected number of registered types", 2,
|
||||
analyzer.getRegisteredTypes().length);
|
||||
assertThat(analyzer.getRegisteredTypes().length).withFailMessage(
|
||||
"Unexpected number of registered types").isEqualTo(2);
|
||||
|
||||
Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]);
|
||||
|
||||
@@ -181,21 +176,26 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
// by default
|
||||
assertThat(chain.length).as("Unexpected chain size").isEqualTo(3);
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
assertThat(chain[i]).isEqualTo("Unexpected chain entry: " + i, this.testTrace[i]);
|
||||
assertThat(chain[i]).withFailMessage(
|
||||
"Unexpected chain entry: " + i).isEqualTo(this.testTrace[i]);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetermineCauseChainWithCustomExtractors() {
|
||||
ThrowableAnalyzer analyzer = this.nonstandardAnalyzer;
|
||||
|
||||
Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]);
|
||||
|
||||
assertThat(chain.length).as("Unexpected chain size").isEqualTo(this.testTrace.length);
|
||||
assertThat(chain.length).as("Unexpected chain size").isEqualTo(
|
||||
this.testTrace.length);
|
||||
for (int i = 0; i < chain.length; ++i) {
|
||||
assertThat(chain[i]).isEqualTo("Unexpected chain entry: " + i, this.testTrace[i]);
|
||||
assertThat(chain[i]).withFailMessage(
|
||||
"Unexpected chain entry: " + i).isEqualTo(this.testTrace[i]);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFirstThrowableOfTypeWithSuccess1() {
|
||||
ThrowableAnalyzer analyzer = this.nonstandardAnalyzer;
|
||||
|
||||
@@ -207,6 +207,7 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
assertThat(result).as("Unexpected throwable found").isEqualTo(this.testTrace[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFirstThrowableOfTypeWithSuccess2() {
|
||||
ThrowableAnalyzer analyzer = this.nonstandardAnalyzer;
|
||||
|
||||
@@ -219,6 +220,7 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
assertThat(result).as("Unexpected throwable found").isEqualTo(this.testTrace[2]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFirstThrowableOfTypeWithFailure() {
|
||||
ThrowableAnalyzer analyzer = this.nonstandardAnalyzer;
|
||||
|
||||
@@ -231,14 +233,16 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
assertThat(result).as("null expected").isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVerifyThrowableHierarchyWithExactType() {
|
||||
|
||||
Throwable throwable = new IllegalStateException("Test");
|
||||
ThrowableAnalyzer
|
||||
.verifyThrowableHierarchy(throwable, IllegalStateException.class);
|
||||
ThrowableAnalyzer.verifyThrowableHierarchy(throwable,
|
||||
IllegalStateException.class);
|
||||
// No exception expected
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVerifyThrowableHierarchyWithCompatibleType() {
|
||||
|
||||
Throwable throwable = new IllegalStateException("Test");
|
||||
@@ -246,6 +250,7 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
// No exception expected
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVerifyThrowableHierarchyWithNull() {
|
||||
try {
|
||||
ThrowableAnalyzer.verifyThrowableHierarchy(null, Throwable.class);
|
||||
@@ -256,6 +261,7 @@ public class ThrowableAnalyzerTests extends TestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testVerifyThrowableHierarchyWithNonmatchingType() {
|
||||
|
||||
Throwable throwable = new IllegalStateException("Test");
|
||||
|
||||
@@ -10,12 +10,10 @@
|
||||
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.util.matcher;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -25,8 +23,6 @@ import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.AnyRequestMatcher;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
@@ -34,6 +30,7 @@ import org.springframework.security.web.util.matcher.AnyRequestMatcher;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class AntPathRequestMatcherTests {
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@@ -157,33 +154,36 @@ public class AntPathRequestMatcherTests {
|
||||
@Test
|
||||
public void caseSensitive() throws Exception {
|
||||
MockHttpServletRequest request = createRequest("/UPPER");
|
||||
assertThat(new AntPathRequestMatcher("/upper", null, true).matches(request))
|
||||
.isFalse();
|
||||
assertThat(new AntPathRequestMatcher("/upper", "POST", true).matches(request))
|
||||
.isFalse();
|
||||
assertThat(new AntPathRequestMatcher("/upper", "GET", true).matches(request))
|
||||
.isFalse();
|
||||
assertThat(new AntPathRequestMatcher("/upper", null, true).matches(
|
||||
request)).isFalse();
|
||||
assertThat(new AntPathRequestMatcher("/upper", "POST", true).matches(
|
||||
request)).isFalse();
|
||||
assertThat(new AntPathRequestMatcher("/upper", "GET", true).matches(
|
||||
request)).isFalse();
|
||||
|
||||
assertThat(new AntPathRequestMatcher("/upper", null, false).matches(request))
|
||||
.isTrue();
|
||||
assertThat(new AntPathRequestMatcher("/upper", "POST", false).matches(request))
|
||||
.isTrue();
|
||||
assertThat(new AntPathRequestMatcher("/upper", null, false).matches(
|
||||
request)).isTrue();
|
||||
assertThat(new AntPathRequestMatcher("/upper", "POST", false).matches(
|
||||
request)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equalsBehavesCorrectly() throws Exception {
|
||||
// Both universal wildcard options should be equal
|
||||
assertThat(new AntPathRequestMatcher("**")).isEqualTo(new AntPathRequestMatcher("/**"));
|
||||
assertThat(new AntPathRequestMatcher("/xyz")).isEqualTo(new AntPathRequestMatcher("/xyz"));
|
||||
assertThat("POST").isEqualTo(new AntPathRequestMatcher("/xyz"),
|
||||
assertThat(new AntPathRequestMatcher("**")).isEqualTo(
|
||||
new AntPathRequestMatcher("/**"));
|
||||
assertThat(new AntPathRequestMatcher("/xyz")).isEqualTo(
|
||||
new AntPathRequestMatcher("/xyz"));
|
||||
assertThat(new AntPathRequestMatcher("/xyz", "POST")).isEqualTo(
|
||||
new AntPathRequestMatcher("/xyz", "POST"));
|
||||
assertThat(new AntPathRequestMatcher("/xyz", "POST").isFalse()
|
||||
.equals(new AntPathRequestMatcher("/xyz", "GET")));
|
||||
assertThat(new AntPathRequestMatcher("/xyz").isFalse().equals(new AntPathRequestMatcher(
|
||||
"/xxx")));
|
||||
assertThat(new AntPathRequestMatcher("/xyz").equals(AnyRequestMatcher.INSTANCE)).isFalse();
|
||||
assertThat(new AntPathRequestMatcher("/xyz", "GET", false).isFalse()
|
||||
.equals(new AntPathRequestMatcher("/xyz", "GET", true)));
|
||||
assertThat(new AntPathRequestMatcher("/xyz", "POST")).isNotEqualTo(
|
||||
new AntPathRequestMatcher("/xyz", "GET"));
|
||||
assertThat(new AntPathRequestMatcher("/xyz")).isNotEqualTo(
|
||||
new AntPathRequestMatcher("/xxx"));
|
||||
assertThat(new AntPathRequestMatcher("/xyz").equals(
|
||||
AnyRequestMatcher.INSTANCE)).isFalse();
|
||||
assertThat(new AntPathRequestMatcher("/xyz", "GET", false)).isNotEqualTo(
|
||||
new AntPathRequestMatcher("/xyz", "GET", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -10,11 +10,10 @@
|
||||
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.security.web.util.matcher;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -24,7 +23,6 @@ import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.security.web.util.matcher.RegexRequestMatcher;
|
||||
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
@@ -32,6 +30,7 @@ import org.springframework.security.web.util.matcher.RegexRequestMatcher;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RegexRequestMatcherTests {
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user