Add JSON Serialization

Fixes gh-3812
This commit is contained in:
Jitendra Singh Bisht
2016-03-30 18:05:30 +05:30
committed by Rob Winch
parent 4d02a5c0a0
commit d77ca17e95
47 changed files with 2791 additions and 69 deletions

View File

@@ -0,0 +1,41 @@
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on 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.jackson2;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.security.jackson2.SecurityJacksonModules;
import org.springframework.util.ObjectUtils;
/**
* @author Jitenra Singh
* @since 4.2
*/
@RunWith(MockitoJUnitRunner.class)
public abstract class AbstractMixinTests {
ObjectMapper mapper;
protected ObjectMapper buildObjectMapper() {
if (ObjectUtils.isEmpty(mapper)) {
mapper = new ObjectMapper();
mapper.registerModules(SecurityJacksonModules.getModules());
}
return mapper;
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on 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.jackson2;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.jackson2.SecurityJacksonModules;
import javax.servlet.http.Cookie;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jitendra Singh
* @since 4.2
*/
public class CookieMixinTests {
String cookieJson = "{\"@class\": \"javax.servlet.http.Cookie\", \"name\": \"demo\", \"value\": \"cookie1\"," +
"\"comment\": null, \"maxAge\": -1, \"path\": null, \"secure\": false, \"version\": 0, \"isHttpOnly\": false, \"domain\": null}";
ObjectMapper buildObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModules(SecurityJacksonModules.getModules());
return mapper;
}
@Test
public void serializeCookie() throws JsonProcessingException, JSONException {
Cookie cookie = new Cookie("demo", "cookie1");
String actualString = buildObjectMapper().writeValueAsString(cookie);
JSONAssert.assertEquals(cookieJson, actualString, true);
}
@Test
public void deserializeCookie() throws IOException {
Cookie cookie = buildObjectMapper().readValue(cookieJson, Cookie.class);
assertThat(cookie).isNotNull();
assertThat(cookie.getName()).isEqualTo("demo");
assertThat(cookie.getDomain()).isEqualTo("");
assertThat(cookie.isHttpOnly()).isEqualTo(false);
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on 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.jackson2;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.jackson2.SecurityJacksonModules;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jitendra Singh
* @since 4.2
*/
@RunWith(MockitoJUnitRunner.class)
public class DefaultCsrfTokenMixinTests {
ObjectMapper objectMapper;
String defaultCsrfTokenJson;
@Before
public void setup() {
objectMapper = new ObjectMapper();
objectMapper.registerModules(SecurityJacksonModules.getModules());
defaultCsrfTokenJson = "{\"@class\": \"org.springframework.security.web.csrf.DefaultCsrfToken\", " +
"\"headerName\": \"csrf-header\", \"parameterName\": \"_csrf\", \"token\": \"1\"}";
}
@Test
public void defaultCsrfTokenSerializedTest() throws JsonProcessingException, JSONException {
DefaultCsrfToken token = new DefaultCsrfToken("csrf-header", "_csrf", "1");
String serializedJson = objectMapper.writeValueAsString(token);
JSONAssert.assertEquals(defaultCsrfTokenJson, serializedJson, true);
}
@Test
public void defaultCsrfTokenDeserializeTest() throws IOException {
DefaultCsrfToken token = objectMapper.readValue(defaultCsrfTokenJson, DefaultCsrfToken.class);
assertThat(token).isNotNull();
assertThat(token.getHeaderName()).isEqualTo("csrf-header");
assertThat(token.getParameterName()).isEqualTo("_csrf");
assertThat(token.getToken()).isEqualTo("1");
}
@Test(expected = JsonMappingException.class)
public void defaultCsrfTokenDeserializeWithoutClassTest() throws IOException {
String tokenJson = "{\"headerName\": \"csrf-header\", \"parameterName\": \"_csrf\", \"token\": \"1\"}";
objectMapper.readValue(tokenJson, DefaultCsrfToken.class);
}
@Test(expected = JsonMappingException.class)
public void defaultCsrfTokenDeserializeNullValuesTest() throws IOException {
String tokenJson = "{\"@class\": \"org.springframework.security.web.csrf.DefaultCsrfToken\", \"headerName\": \"\", \"parameterName\": null, \"token\": \"1\"}";
objectMapper.readValue(tokenJson, DefaultCsrfToken.class);
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on 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.jackson2;
import org.json.JSONException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.PortResolverImpl;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.security.web.savedrequest.SavedCookie;
import javax.servlet.http.Cookie;
import java.io.IOException;
import java.util.Collections;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jitendra Singh
* @since 4.2
*/
@RunWith(MockitoJUnitRunner.class)
public class DefaultSavedRequestMixinTests extends AbstractMixinTests {
String defaultSavedRequestJson = "{" +
"\"@class\": \"org.springframework.security.web.savedrequest.DefaultSavedRequest\", \"cookies\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.web.savedrequest.SavedCookie\", \"name\": \"SESSION\", \"value\": \"123456789\", \"comment\": null, \"maxAge\": -1, \"path\": null, \"secure\":false, \"version\": 0, \"domain\": null}]]," +
"\"locales\": [\"java.util.ArrayList\", [\"en\"]], \"headers\": {\"@class\": \"java.util.TreeMap\", \"x-auth-token\": [\"java.util.ArrayList\", [\"12\"]]}, \"parameters\": {\"@class\": \"java.util.TreeMap\"}," +
"\"contextPath\": \"\", \"method\": \"\", \"pathInfo\": null, \"queryString\": null, \"requestURI\": \"\", \"requestURL\": \"http://localhost\", \"scheme\": \"http\", " +
"\"serverName\": \"localhost\", \"servletPath\": \"\", \"serverPort\": 80"+
"}";
@Test
public void matchRequestBuildWithConstructorAndBuilder() {
DefaultSavedRequest request = new DefaultSavedRequest.Builder()
.setCookies(Collections.singletonList(new SavedCookie(new Cookie("SESSION", "123456789"))))
.setHeaders(Collections.singletonMap("x-auth-token", Collections.singletonList("12")))
.setScheme("http").setRequestURL("http://localhost").setServerName("localhost").setRequestURI("")
.setLocales(Collections.singletonList(new Locale("en"))).setContextPath("").setMethod("")
.setServletPath("").build();
MockHttpServletRequest mockRequest = new MockHttpServletRequest();
mockRequest.setCookies(new Cookie("SESSION", "123456789"));
mockRequest.addHeader("x-auth-token", "12");
assert request.doesRequestMatch(mockRequest, new PortResolverImpl());
}
@Test
public void serializeDefaultRequestBuildWithConstructorTest() throws IOException, JSONException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(new Cookie("SESSION", "123456789"));
request.addHeader("x-auth-token", "12");
String actualString = buildObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(new DefaultSavedRequest(request, new PortResolverImpl()));
JSONAssert.assertEquals(defaultSavedRequestJson, actualString, true);
}
@Test
public void serializeDefaultRequestBuildWithBuilderTest() throws IOException, JSONException {
DefaultSavedRequest request = new DefaultSavedRequest.Builder()
.setCookies(Collections.singletonList(new SavedCookie(new Cookie("SESSION", "123456789"))))
.setHeaders(Collections.singletonMap("x-auth-token", Collections.singletonList("12")))
.setScheme("http").setRequestURL("http://localhost").setServerName("localhost").setRequestURI("")
.setLocales(Collections.singletonList(new Locale("en"))).setContextPath("").setMethod("")
.setServletPath("").build();
String actualString = buildObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(request);
JSONAssert.assertEquals(defaultSavedRequestJson, actualString, true);
}
@Test
public void deserializeDefaultSavedRequest() throws IOException {
DefaultSavedRequest request = (DefaultSavedRequest) buildObjectMapper().readValue(defaultSavedRequestJson, Object.class);
assertThat(request).isNotNull();
assertThat(request.getCookies()).hasSize(1);
assertThat(request.getLocales()).hasSize(1).contains(new Locale("en"));
assertThat(request.getHeaderNames()).hasSize(1).contains("x-auth-token");
assertThat(request.getHeaderValues("x-auth-token")).hasSize(1).contains("12");
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on 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.jackson2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.web.savedrequest.SavedCookie;
import javax.servlet.http.Cookie;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jitendra Singh.
*/
public class SavedCookieMixinTests extends AbstractMixinTests {
private String expectedSavedCookieJson;
@Before
public void setup() {
expectedSavedCookieJson = "{\"@class\": \"org.springframework.security.web.savedrequest.SavedCookie\", " +
"\"name\": \"session\", \"value\": \"123456\", \"comment\": null, \"domain\": null, \"maxAge\": -1, " +
"\"path\": null, \"secure\": false, \"version\": 0}";
}
@Test
public void serializeWithDefaultConfigurationTest() throws JsonProcessingException, JSONException {
SavedCookie savedCookie = new SavedCookie(new Cookie("session", "123456"));
String actualJson = buildObjectMapper().writeValueAsString(savedCookie);
JSONAssert.assertEquals(expectedSavedCookieJson, actualJson, true);
}
@Test
public void serializeWithOverrideConfigurationTest() throws JsonProcessingException, JSONException {
SavedCookie savedCookie = new SavedCookie(new Cookie("session", "123456"));
ObjectMapper mapper = buildObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PUBLIC_ONLY)
.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.ANY);
String actualJson = mapper.writeValueAsString(savedCookie);
JSONAssert.assertEquals(expectedSavedCookieJson, actualJson, true);
}
@Test
public void serializeSavedCookieWithList() throws JsonProcessingException, JSONException {
List<SavedCookie> savedCookies = new ArrayList<SavedCookie>();
savedCookies.add(new SavedCookie(new Cookie("session", "123456")));
String expectedJson = String.format("[\"java.util.ArrayList\", [%s]]", expectedSavedCookieJson);
String actualJson = buildObjectMapper().writeValueAsString(savedCookies);
JSONAssert.assertEquals(expectedJson, actualJson, true);
}
@Test
public void deserializeSavedCookieWithList() throws IOException, JSONException {
String expectedJson = String.format("[\"java.util.ArrayList\", [%s]]", expectedSavedCookieJson);
List<SavedCookie> savedCookies = (List<SavedCookie>)buildObjectMapper().readValue(expectedJson, Object.class);
assertThat(savedCookies).isNotNull().hasSize(1);
assertThat(savedCookies.get(0).getName()).isEqualTo("session");
assertThat(savedCookies.get(0).getValue()).isEqualTo("123456");
}
@Test
public void deserializeSavedCookieJsonTest() throws IOException {
SavedCookie savedCookie = (SavedCookie) buildObjectMapper().readValue(expectedSavedCookieJson, Object.class);
assertThat(savedCookie).isNotNull();
assertThat(savedCookie.getName()).isEqualTo("session");
assertThat(savedCookie.getValue()).isEqualTo("123456");
assertThat(savedCookie.isSecure()).isEqualTo(false);
assertThat(savedCookie.getVersion()).isEqualTo(0);
assertThat(savedCookie.getComment()).isNull();
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on 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.jackson2;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.jackson2.SecurityJacksonModules;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Jitendra Singh
* @since 4.2
*/
@RunWith(MockitoJUnitRunner.class)
public class WebAuthenticationDetailsMixinTests {
ObjectMapper mapper;
String webAuthenticationDetailsJson = "{\"@class\": \"org.springframework.security.web.authentication.WebAuthenticationDetails\","
+ "\"sessionId\": \"1\", \"remoteAddress\": \"/localhost\"}";
@Before
public void setup() {
this.mapper = new ObjectMapper();
this.mapper.registerModules(SecurityJacksonModules.getModules());
}
@Test
public void buildWebAuthenticationDetailsUsingDifferentConstructors()
throws IOException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRemoteAddr("localhost");
request.setSession(new MockHttpSession(null, "1"));
WebAuthenticationDetails details = new WebAuthenticationDetails(request);
WebAuthenticationDetails authenticationDetails = this.mapper.readValue(webAuthenticationDetailsJson,
WebAuthenticationDetails.class);
assertThat(details.equals(authenticationDetails));
}
@Test
public void webAuthenticationDetailsSerializeTest()
throws JsonProcessingException, JSONException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRemoteAddr("/localhost");
request.setSession(new MockHttpSession(null, "1"));
WebAuthenticationDetails details = new WebAuthenticationDetails(request);
String actualJson = this.mapper.writeValueAsString(details);
JSONAssert.assertEquals(webAuthenticationDetailsJson, actualJson, true);
}
@Test
public void webAuthenticationDetailsDeserializeTest()
throws IOException, JSONException {
WebAuthenticationDetails details = this.mapper.readValue(webAuthenticationDetailsJson,
WebAuthenticationDetails.class);
assertThat(details).isNotNull();
assertThat(details.getRemoteAddress()).isEqualTo("/localhost");
assertThat(details.getSessionId()).isEqualTo("1");
}
}