JSON tests ObjectMapper Cleanup

* Move to @Setup
* Consistently extend from AbstractMixinTests and reuse ObjectMapper

Issue gh-3736
This commit is contained in:
Rob Winch 2016-09-02 11:10:54 -05:00
parent bd925313af
commit 3531cc93c2
14 changed files with 72 additions and 117 deletions

View File

@ -27,6 +27,7 @@ import org.jasig.cas.client.authentication.AttributePrincipalImpl;
import org.jasig.cas.client.validation.Assertion; import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl; import org.jasig.cas.client.validation.AssertionImpl;
import org.json.JSONException; import org.json.JSONException;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONAssert;
@ -96,10 +97,19 @@ public class CasAuthenticationTokenMixinTests {
private static final String CAS_TOKEN_CLEARED_JSON = CAS_TOKEN_JSON.replaceFirst(PASSWORD, "null"); private static final String CAS_TOKEN_CLEARED_JSON = CAS_TOKEN_JSON.replaceFirst(PASSWORD, "null");
protected ObjectMapper mapper;
@Before
public void setup() {
mapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader();
mapper.registerModules(SecurityJacksonModules.getModules(loader));
}
@Test @Test
public void serializeCasAuthenticationTest() throws JsonProcessingException, JSONException { public void serializeCasAuthenticationTest() throws JsonProcessingException, JSONException {
CasAuthenticationToken token = createCasAuthenticationToken(); CasAuthenticationToken token = createCasAuthenticationToken();
String actualJson = buildObjectMapper().writeValueAsString(token); String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(CAS_TOKEN_JSON, actualJson, true); JSONAssert.assertEquals(CAS_TOKEN_JSON, actualJson, true);
} }
@ -107,19 +117,19 @@ public class CasAuthenticationTokenMixinTests {
public void serializeCasAuthenticationTestAfterEraseCredentialInvoked() throws JsonProcessingException, JSONException { public void serializeCasAuthenticationTestAfterEraseCredentialInvoked() throws JsonProcessingException, JSONException {
CasAuthenticationToken token = createCasAuthenticationToken(); CasAuthenticationToken token = createCasAuthenticationToken();
token.eraseCredentials(); token.eraseCredentials();
String actualJson = buildObjectMapper().writeValueAsString(token); String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(CAS_TOKEN_CLEARED_JSON, actualJson, true); JSONAssert.assertEquals(CAS_TOKEN_CLEARED_JSON, actualJson, true);
} }
@Test @Test
public void deserializeCasAuthenticationTestAfterEraseCredentialInvoked() throws Exception { public void deserializeCasAuthenticationTestAfterEraseCredentialInvoked() throws Exception {
CasAuthenticationToken token = buildObjectMapper().readValue(CAS_TOKEN_CLEARED_JSON, CasAuthenticationToken.class); CasAuthenticationToken token = mapper.readValue(CAS_TOKEN_CLEARED_JSON, CasAuthenticationToken.class);
assertThat(((UserDetails)token.getPrincipal()).getPassword()).isNull(); assertThat(((UserDetails)token.getPrincipal()).getPassword()).isNull();
} }
@Test @Test
public void deserializeCasAuthenticationTest() throws IOException, JSONException { public void deserializeCasAuthenticationTest() throws IOException, JSONException {
CasAuthenticationToken token = buildObjectMapper().readValue(CAS_TOKEN_JSON, CasAuthenticationToken.class); CasAuthenticationToken token = mapper.readValue(CAS_TOKEN_JSON, CasAuthenticationToken.class);
assertThat(token).isNotNull(); assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class); assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
assertThat(((User) token.getPrincipal()).getUsername()).isEqualTo("admin"); assertThat(((User) token.getPrincipal()).getUsername()).isEqualTo("admin");
@ -142,11 +152,4 @@ public class CasAuthenticationTokenMixinTests {
return new CasAuthenticationToken(KEY, principal, principal.getPassword(), authorities, return new CasAuthenticationToken(KEY, principal, principal.getPassword(), authorities,
new User("admin", "1234", authorities), assertion); new User("admin", "1234", authorities), assertion);
} }
ObjectMapper buildObjectMapper() {
ClassLoader loader = getClass().getClassLoader();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModules(SecurityJacksonModules.getModules(loader));
return mapper;
}
} }

View File

@ -17,26 +17,23 @@
package org.springframework.security.jackson2; package org.springframework.security.jackson2;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
import org.springframework.util.ObjectUtils;
/** /**
* @author Jitenra Singh * @author Jitenra Singh
* @since 4.2 * @since 4.2
*/ */
public abstract class AbstractMixinTests { public abstract class AbstractMixinTests {
protected ObjectMapper mapper;
ObjectMapper mapper; @Before
public void setup() {
protected ObjectMapper buildObjectMapper() { mapper = new ObjectMapper();
if (ObjectUtils.isEmpty(mapper)) { ClassLoader loader = getClass().getClassLoader();
mapper = new ObjectMapper(); mapper.registerModules(SecurityJacksonModules.getModules(loader));
ClassLoader loader = getClass().getClassLoader();
mapper.registerModules(SecurityJacksonModules.getModules(loader));
}
return mapper;
} }
User createDefaultUser() { User createDefaultUser() {

View File

@ -56,13 +56,13 @@ public class AnonymousAuthenticationTokenMixinTests extends AbstractMixinTests {
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken( AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(
HASH_KEY, user, user.getAuthorities() HASH_KEY, user, user.getAuthorities()
); );
String actualJson = buildObjectMapper().writeValueAsString(token); String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(ANONYMOUS_JSON, actualJson, true); JSONAssert.assertEquals(ANONYMOUS_JSON, actualJson, true);
} }
@Test @Test
public void deserializeAnonymousAuthenticationTokenTest() throws IOException { public void deserializeAnonymousAuthenticationTokenTest() throws IOException {
AnonymousAuthenticationToken token = buildObjectMapper() AnonymousAuthenticationToken token = mapper
.readValue(ANONYMOUS_JSON, AnonymousAuthenticationToken.class); .readValue(ANONYMOUS_JSON, AnonymousAuthenticationToken.class);
assertThat(token).isNotNull(); assertThat(token).isNotNull();
assertThat(token.getKeyHash()).isEqualTo(HASH_KEY.hashCode()); assertThat(token.getKeyHash()).isEqualTo(HASH_KEY.hashCode());
@ -74,7 +74,7 @@ public class AnonymousAuthenticationTokenMixinTests extends AbstractMixinTests {
String jsonString = "{\"@class\": \"org.springframework.security.authentication.AnonymousAuthenticationToken\", \"details\": null," + String jsonString = "{\"@class\": \"org.springframework.security.authentication.AnonymousAuthenticationToken\", \"details\": null," +
"\"principal\": \"user\", \"authenticated\": true, \"keyHash\": " + HASH_KEY.hashCode() + "," + "\"principal\": \"user\", \"authenticated\": true, \"keyHash\": " + HASH_KEY.hashCode() + "," +
"\"authorities\": [\"java.util.ArrayList\", []]}"; "\"authorities\": [\"java.util.ArrayList\", []]}";
buildObjectMapper().readValue(jsonString, AnonymousAuthenticationToken.class); mapper.readValue(jsonString, AnonymousAuthenticationToken.class);
} }
@Test @Test
@ -84,7 +84,7 @@ public class AnonymousAuthenticationTokenMixinTests extends AbstractMixinTests {
HASH_KEY, user, user.getAuthorities() HASH_KEY, user, user.getAuthorities()
); );
token.eraseCredentials(); token.eraseCredentials();
String actualJson = buildObjectMapper().writeValueAsString(token); String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(ANONYMOUS_JSON.replace(UserDeserializerTests.USER_PASSWORD, "null"), actualJson, true); JSONAssert.assertEquals(ANONYMOUS_JSON.replace(UserDeserializerTests.USER_PASSWORD, "null"), actualJson, true);
} }
} }

View File

@ -72,7 +72,7 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
@Test @Test
public void serializeRememberMeAuthenticationToken() throws JsonProcessingException, JSONException { public void serializeRememberMeAuthenticationToken() throws JsonProcessingException, JSONException {
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, "admin", Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"))); RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, "admin", Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")));
String actualJson = buildObjectMapper().writeValueAsString(token); String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(REMEMBERME_AUTH_STRINGPRINCIPAL_JSON, actualJson, true); JSONAssert.assertEquals(REMEMBERME_AUTH_STRINGPRINCIPAL_JSON, actualJson, true);
} }
@ -80,7 +80,7 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
public void serializeRememberMeAuthenticationWithUserToken() throws JsonProcessingException, JSONException { public void serializeRememberMeAuthenticationWithUserToken() throws JsonProcessingException, JSONException {
User user = createDefaultUser(); User user = createDefaultUser();
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, user, user.getAuthorities()); RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, user, user.getAuthorities());
String actualJson = buildObjectMapper().writeValueAsString(token); String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(String.format(REMEMBERME_AUTH_JSON, "\"password\""), actualJson, true); JSONAssert.assertEquals(String.format(REMEMBERME_AUTH_JSON, "\"password\""), actualJson, true);
} }
@ -89,13 +89,13 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
User user = createDefaultUser(); User user = createDefaultUser();
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, user, user.getAuthorities()); RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(REMEMBERME_KEY, user, user.getAuthorities());
token.eraseCredentials(); token.eraseCredentials();
String actualJson = buildObjectMapper().writeValueAsString(token); String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(REMEMBERME_AUTH_JSON.replace(UserDeserializerTests.USER_PASSWORD, "null"), actualJson, true); JSONAssert.assertEquals(REMEMBERME_AUTH_JSON.replace(UserDeserializerTests.USER_PASSWORD, "null"), actualJson, true);
} }
@Test @Test
public void deserializeRememberMeAuthenticationToken() throws IOException { public void deserializeRememberMeAuthenticationToken() throws IOException {
RememberMeAuthenticationToken token = buildObjectMapper().readValue(REMEMBERME_AUTH_STRINGPRINCIPAL_JSON, RememberMeAuthenticationToken.class); RememberMeAuthenticationToken token = mapper.readValue(REMEMBERME_AUTH_STRINGPRINCIPAL_JSON, RememberMeAuthenticationToken.class);
assertThat(token).isNotNull(); assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isEqualTo("admin").isEqualTo(token.getName()); assertThat(token.getPrincipal()).isNotNull().isEqualTo("admin").isEqualTo(token.getName());
assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER")); assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
@ -103,7 +103,7 @@ public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests
@Test @Test
public void deserializeRememberMeAuthenticationTokenWithUserTest() throws IOException { public void deserializeRememberMeAuthenticationTokenWithUserTest() throws IOException {
RememberMeAuthenticationToken token = buildObjectMapper() RememberMeAuthenticationToken token = mapper
.readValue(String.format(REMEMBERME_AUTH_JSON, "\"password\""), RememberMeAuthenticationToken.class); .readValue(String.format(REMEMBERME_AUTH_JSON, "\"password\""), RememberMeAuthenticationToken.class);
assertThat(token).isNotNull(); assertThat(token).isNotNull();
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class); assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);

View File

@ -47,13 +47,13 @@ public class SecurityContextMixinTests extends AbstractMixinTests {
public void securityContextSerializeTest() throws JsonProcessingException, JSONException { public void securityContextSerializeTest() throws JsonProcessingException, JSONException {
SecurityContext context = new SecurityContextImpl(); SecurityContext context = new SecurityContextImpl();
context.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "1234", Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")))); context.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "1234", Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"))));
String actualJson = buildObjectMapper().writeValueAsString(context); String actualJson = mapper.writeValueAsString(context);
JSONAssert.assertEquals(SECURITY_CONTEXT_JSON, actualJson, true); JSONAssert.assertEquals(SECURITY_CONTEXT_JSON, actualJson, true);
} }
@Test @Test
public void securityContextDeserializeTest() throws IOException { public void securityContextDeserializeTest() throws IOException {
SecurityContext context = buildObjectMapper().readValue(SECURITY_CONTEXT_JSON, SecurityContextImpl.class); SecurityContext context = mapper.readValue(SECURITY_CONTEXT_JSON, SecurityContextImpl.class);
assertThat(context).isNotNull(); assertThat(context).isNotNull();
assertThat(context.getAuthentication()).isNotNull().isInstanceOf(UsernamePasswordAuthenticationToken.class); assertThat(context.getAuthentication()).isNotNull().isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isEqualTo("admin"); assertThat(context.getAuthentication().getPrincipal()).isEqualTo("admin");

View File

@ -48,13 +48,13 @@ public class SimpleGrantedAuthorityMixinTests extends AbstractMixinTests {
@Test @Test
public void serializeSimpleGrantedAuthorityTest() throws JsonProcessingException, JSONException { public void serializeSimpleGrantedAuthorityTest() throws JsonProcessingException, JSONException {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER"); SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
String serializeJson = buildObjectMapper().writeValueAsString(authority); String serializeJson = mapper.writeValueAsString(authority);
JSONAssert.assertEquals(AUTHORITY_JSON, serializeJson, true); JSONAssert.assertEquals(AUTHORITY_JSON, serializeJson, true);
} }
@Test @Test
public void deserializeGrantedAuthorityTest() throws IOException { public void deserializeGrantedAuthorityTest() throws IOException {
SimpleGrantedAuthority authority = buildObjectMapper().readValue(AUTHORITY_JSON, SimpleGrantedAuthority.class); SimpleGrantedAuthority authority = mapper.readValue(AUTHORITY_JSON, SimpleGrantedAuthority.class);
assertThat(authority).isNotNull(); assertThat(authority).isNotNull();
assertThat(authority.getAuthority()).isNotNull().isEqualTo("ROLE_USER"); assertThat(authority.getAuthority()).isNotNull().isEqualTo("ROLE_USER");
} }
@ -62,6 +62,6 @@ public class SimpleGrantedAuthorityMixinTests extends AbstractMixinTests {
@Test(expected = JsonMappingException.class) @Test(expected = JsonMappingException.class)
public void deserializeGrantedAuthorityWithoutRoleTest() throws IOException { public void deserializeGrantedAuthorityWithoutRoleTest() throws IOException {
String json = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\"}"; String json = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\"}";
buildObjectMapper().readValue(json, SimpleGrantedAuthority.class); mapper.readValue(json, SimpleGrantedAuthority.class);
} }
} }

View File

@ -55,7 +55,6 @@ public class UserDeserializerTests extends AbstractMixinTests {
@Test @Test
public void serializeUserTest() throws JsonProcessingException, JSONException { public void serializeUserTest() throws JsonProcessingException, JSONException {
ObjectMapper mapper = buildObjectMapper();
User user = createDefaultUser(); User user = createDefaultUser();
String userJson = mapper.writeValueAsString(user); String userJson = mapper.writeValueAsString(user);
JSONAssert.assertEquals(userWithPasswordJson(user.getPassword()), userJson, true); JSONAssert.assertEquals(userWithPasswordJson(user.getPassword()), userJson, true);
@ -63,7 +62,6 @@ public class UserDeserializerTests extends AbstractMixinTests {
@Test @Test
public void serializeUserWithoutAuthority() throws JsonProcessingException, JSONException { public void serializeUserWithoutAuthority() throws JsonProcessingException, JSONException {
ObjectMapper mapper = buildObjectMapper();
User user = new User("admin", "1234", Collections.<GrantedAuthority>emptyList()); User user = new User("admin", "1234", Collections.<GrantedAuthority>emptyList());
String userJson = mapper.writeValueAsString(user); String userJson = mapper.writeValueAsString(user);
JSONAssert.assertEquals(userWithNoAuthoritiesJson(), userJson, true); JSONAssert.assertEquals(userWithNoAuthoritiesJson(), userJson, true);
@ -73,14 +71,11 @@ public class UserDeserializerTests extends AbstractMixinTests {
public void deserializeUserWithNullPasswordEmptyAuthorityTest() throws IOException { public void deserializeUserWithNullPasswordEmptyAuthorityTest() throws IOException {
String userJsonWithoutPasswordString = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON, "[]"); String userJsonWithoutPasswordString = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON, "[]");
ObjectMapper mapper = buildObjectMapper();
mapper.readValue(userJsonWithoutPasswordString, User.class); mapper.readValue(userJsonWithoutPasswordString, User.class);
} }
@Test @Test
public void deserializeUserWithNullPasswordNoAuthorityTest() throws Exception { public void deserializeUserWithNullPasswordNoAuthorityTest() throws Exception {
ObjectMapper mapper = buildObjectMapper();
String userJsonWithoutPasswordString = removeNode(userWithNoAuthoritiesJson(), mapper, "password"); String userJsonWithoutPasswordString = removeNode(userWithNoAuthoritiesJson(), mapper, "password");
User user = mapper.readValue(userJsonWithoutPasswordString, User.class); User user = mapper.readValue(userJsonWithoutPasswordString, User.class);
@ -93,14 +88,13 @@ public class UserDeserializerTests extends AbstractMixinTests {
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void deserializeUserWithNoClassIdInAuthoritiesTest() throws Exception { public void deserializeUserWithNoClassIdInAuthoritiesTest() throws Exception {
ObjectMapper mapper = buildObjectMapper();
String userJson = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON, "[{\"authority\": \"ROLE_USER\"}]"); String userJson = USER_JSON.replace(SimpleGrantedAuthorityMixinTests.AUTHORITIES_SET_JSON, "[{\"authority\": \"ROLE_USER\"}]");
mapper.readValue(userJson, User.class); mapper.readValue(userJson, User.class);
} }
@Test @Test
public void deserializeUserWithClassIdInAuthoritiesTest() throws IOException { public void deserializeUserWithClassIdInAuthoritiesTest() throws IOException {
User user = buildObjectMapper().readValue(userJson(), User.class); User user = mapper.readValue(userJson(), User.class);
assertThat(user).isNotNull(); assertThat(user).isNotNull();
assertThat(user.getUsername()).isEqualTo("admin"); assertThat(user.getUsername()).isEqualTo("admin");
assertThat(user.getPassword()).isEqualTo("1234"); assertThat(user.getPassword()).isEqualTo("1234");

View File

@ -19,7 +19,6 @@ package org.springframework.security.jackson2;
import java.io.IOException; import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException; import org.json.JSONException;
import org.junit.Test; import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONAssert;
@ -59,7 +58,7 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
@Test @Test
public void serializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws JsonProcessingException, JSONException { public void serializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws JsonProcessingException, JSONException {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("admin", "1234"); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("admin", "1234");
String serializedJson = buildObjectMapper().writeValueAsString(token); String serializedJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(UNAUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true); JSONAssert.assertEquals(UNAUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true);
} }
@ -67,13 +66,13 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws JsonProcessingException, JSONException { public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws JsonProcessingException, JSONException {
User user = createDefaultUser(); User user = createDefaultUser();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities()); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
String serializedJson = buildObjectMapper().writeValueAsString(token); String serializedJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true); JSONAssert.assertEquals(AUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true);
} }
@Test @Test
public void deserializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException, JSONException { public void deserializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException, JSONException {
UsernamePasswordAuthenticationToken token = buildObjectMapper() UsernamePasswordAuthenticationToken token = mapper
.readValue(UNAUTHENTICATED_STRINGPRINCIPAL_JSON, UsernamePasswordAuthenticationToken.class); .readValue(UNAUTHENTICATED_STRINGPRINCIPAL_JSON, UsernamePasswordAuthenticationToken.class);
assertThat(token).isNotNull(); assertThat(token).isNotNull();
assertThat(token.isAuthenticated()).isEqualTo(false); assertThat(token.isAuthenticated()).isEqualTo(false);
@ -83,7 +82,7 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
@Test @Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException { public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException {
UsernamePasswordAuthenticationToken expectedToken = createToken(); UsernamePasswordAuthenticationToken expectedToken = createToken();
UsernamePasswordAuthenticationToken token = buildObjectMapper() UsernamePasswordAuthenticationToken token = mapper
.readValue(AUTHENTICATED_STRINGPRINCIPAL_JSON, UsernamePasswordAuthenticationToken.class); .readValue(AUTHENTICATED_STRINGPRINCIPAL_JSON, UsernamePasswordAuthenticationToken.class);
assertThat(token).isNotNull(); assertThat(token).isNotNull();
assertThat(token.isAuthenticated()).isTrue(); assertThat(token.isAuthenticated()).isTrue();
@ -93,13 +92,12 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
@Test @Test
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinWithUserTest() throws JsonProcessingException, JSONException { public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinWithUserTest() throws JsonProcessingException, JSONException {
UsernamePasswordAuthenticationToken token = createToken(); UsernamePasswordAuthenticationToken token = createToken();
String actualJson = buildObjectMapper().writeValueAsString(token); String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_JSON, actualJson, true); JSONAssert.assertEquals(AUTHENTICATED_JSON, actualJson, true);
} }
@Test @Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithUserTest() throws IOException { public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithUserTest() throws IOException {
ObjectMapper mapper = buildObjectMapper();
UsernamePasswordAuthenticationToken token = mapper UsernamePasswordAuthenticationToken token = mapper
.readValue(AUTHENTICATED_JSON, UsernamePasswordAuthenticationToken.class); .readValue(AUTHENTICATED_JSON, UsernamePasswordAuthenticationToken.class);
assertThat(token).isNotNull(); assertThat(token).isNotNull();
@ -113,7 +111,7 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinAfterEraseCredentialInvoked() throws JsonProcessingException, JSONException { public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinAfterEraseCredentialInvoked() throws JsonProcessingException, JSONException {
UsernamePasswordAuthenticationToken token = createToken(); UsernamePasswordAuthenticationToken token = createToken();
token.eraseCredentials(); token.eraseCredentials();
String actualJson = buildObjectMapper().writeValueAsString(token); String actualJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(AUTHENTICATED_JSON.replaceAll(UserDeserializerTests.USER_PASSWORD, "null"), actualJson, true); JSONAssert.assertEquals(AUTHENTICATED_JSON.replaceAll(UserDeserializerTests.USER_PASSWORD, "null"), actualJson, true);
} }

View File

@ -17,9 +17,9 @@
package org.springframework.security.web.jackson2; package org.springframework.security.web.jackson2;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.springframework.security.jackson2.SecurityJacksonModules; import org.springframework.security.jackson2.SecurityJacksonModules;
import org.springframework.util.ObjectUtils;
/** /**
* @author Jitenra Singh * @author Jitenra Singh
@ -27,14 +27,12 @@ import org.springframework.util.ObjectUtils;
*/ */
public abstract class AbstractMixinTests { public abstract class AbstractMixinTests {
ObjectMapper mapper; protected ObjectMapper mapper;
protected ObjectMapper buildObjectMapper() { @Before
if (ObjectUtils.isEmpty(mapper)) { public void setup() {
mapper = new ObjectMapper(); mapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader(); ClassLoader loader = getClass().getClassLoader();
mapper.registerModules(SecurityJacksonModules.getModules(loader)); mapper.registerModules(SecurityJacksonModules.getModules(loader));
}
return mapper;
} }
} }

View File

@ -16,15 +16,14 @@
package org.springframework.security.web.jackson2; package org.springframework.security.web.jackson2;
import java.io.IOException;
import javax.servlet.http.Cookie;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException; import org.json.JSONException;
import org.junit.Test; import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert; 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; import static org.assertj.core.api.Assertions.assertThat;
@ -32,7 +31,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Jitendra Singh * @author Jitendra Singh
* @since 4.2 * @since 4.2
*/ */
public class CookieMixinTests { public class CookieMixinTests extends AbstractMixinTests {
// @formatter:off // @formatter:off
private static final String COOKIE_JSON = "{" private static final String COOKIE_JSON = "{"
@ -49,23 +48,16 @@ public class CookieMixinTests {
+ "}"; + "}";
// @formatter:on // @formatter:on
ObjectMapper buildObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader();
mapper.registerModules(SecurityJacksonModules.getModules(loader));
return mapper;
}
@Test @Test
public void serializeCookie() throws JsonProcessingException, JSONException { public void serializeCookie() throws JsonProcessingException, JSONException {
Cookie cookie = new Cookie("demo", "cookie1"); Cookie cookie = new Cookie("demo", "cookie1");
String actualString = buildObjectMapper().writeValueAsString(cookie); String actualString = mapper.writeValueAsString(cookie);
JSONAssert.assertEquals(COOKIE_JSON, actualString, true); JSONAssert.assertEquals(COOKIE_JSON, actualString, true);
} }
@Test @Test
public void deserializeCookie() throws IOException { public void deserializeCookie() throws IOException {
Cookie cookie = buildObjectMapper().readValue(COOKIE_JSON, Cookie.class); Cookie cookie = mapper.readValue(COOKIE_JSON, Cookie.class);
assertThat(cookie).isNotNull(); assertThat(cookie).isNotNull();
assertThat(cookie.getName()).isEqualTo("demo"); assertThat(cookie.getName()).isEqualTo("demo");
assertThat(cookie.getDomain()).isEqualTo(""); assertThat(cookie.getDomain()).isEqualTo("");

View File

@ -20,13 +20,10 @@ import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException; import org.json.JSONException;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.security.jackson2.SecurityJacksonModules;
import org.springframework.security.web.csrf.DefaultCsrfToken; import org.springframework.security.web.csrf.DefaultCsrfToken;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -35,11 +32,8 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Jitendra Singh * @author Jitendra Singh
* @since 4.2 * @since 4.2
*/ */
public class DefaultCsrfTokenMixinTests { public class DefaultCsrfTokenMixinTests extends AbstractMixinTests {
ObjectMapper objectMapper;
// @formatter:off // @formatter:off
public static final String CSRF_JSON = "{" public static final String CSRF_JSON = "{"
+ "\"@class\": \"org.springframework.security.web.csrf.DefaultCsrfToken\", " + "\"@class\": \"org.springframework.security.web.csrf.DefaultCsrfToken\", "
@ -49,23 +43,16 @@ public class DefaultCsrfTokenMixinTests {
+ "}"; + "}";
// @formatter:on // @formatter:on
@Before
public void setup() {
objectMapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader();
objectMapper.registerModules(SecurityJacksonModules.getModules(loader));
}
@Test @Test
public void defaultCsrfTokenSerializedTest() throws JsonProcessingException, JSONException { public void defaultCsrfTokenSerializedTest() throws JsonProcessingException, JSONException {
DefaultCsrfToken token = new DefaultCsrfToken("csrf-header", "_csrf", "1"); DefaultCsrfToken token = new DefaultCsrfToken("csrf-header", "_csrf", "1");
String serializedJson = objectMapper.writeValueAsString(token); String serializedJson = mapper.writeValueAsString(token);
JSONAssert.assertEquals(CSRF_JSON, serializedJson, true); JSONAssert.assertEquals(CSRF_JSON, serializedJson, true);
} }
@Test @Test
public void defaultCsrfTokenDeserializeTest() throws IOException { public void defaultCsrfTokenDeserializeTest() throws IOException {
DefaultCsrfToken token = objectMapper.readValue(CSRF_JSON, DefaultCsrfToken.class); DefaultCsrfToken token = mapper.readValue(CSRF_JSON, DefaultCsrfToken.class);
assertThat(token).isNotNull(); assertThat(token).isNotNull();
assertThat(token.getHeaderName()).isEqualTo("csrf-header"); assertThat(token.getHeaderName()).isEqualTo("csrf-header");
assertThat(token.getParameterName()).isEqualTo("_csrf"); assertThat(token.getParameterName()).isEqualTo("_csrf");
@ -75,12 +62,12 @@ public class DefaultCsrfTokenMixinTests {
@Test(expected = JsonMappingException.class) @Test(expected = JsonMappingException.class)
public void defaultCsrfTokenDeserializeWithoutClassTest() throws IOException { public void defaultCsrfTokenDeserializeWithoutClassTest() throws IOException {
String tokenJson = "{\"headerName\": \"csrf-header\", \"parameterName\": \"_csrf\", \"token\": \"1\"}"; String tokenJson = "{\"headerName\": \"csrf-header\", \"parameterName\": \"_csrf\", \"token\": \"1\"}";
objectMapper.readValue(tokenJson, DefaultCsrfToken.class); mapper.readValue(tokenJson, DefaultCsrfToken.class);
} }
@Test(expected = JsonMappingException.class) @Test(expected = JsonMappingException.class)
public void defaultCsrfTokenDeserializeNullValuesTest() throws IOException { public void defaultCsrfTokenDeserializeNullValuesTest() throws IOException {
String tokenJson = "{\"@class\": \"org.springframework.security.web.csrf.DefaultCsrfToken\", \"headerName\": \"\", \"parameterName\": null, \"token\": \"1\"}"; String tokenJson = "{\"@class\": \"org.springframework.security.web.csrf.DefaultCsrfToken\", \"headerName\": \"\", \"parameterName\": null, \"token\": \"1\"}";
objectMapper.readValue(tokenJson, DefaultCsrfToken.class); mapper.readValue(tokenJson, DefaultCsrfToken.class);
} }
} }

View File

@ -94,7 +94,7 @@ public class DefaultSavedRequestMixinTests extends AbstractMixinTests {
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(new Cookie("SESSION", "123456789")); request.setCookies(new Cookie("SESSION", "123456789"));
request.addHeader("x-auth-token", "12"); request.addHeader("x-auth-token", "12");
String actualString = buildObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(new DefaultSavedRequest(request, new PortResolverImpl())); String actualString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new DefaultSavedRequest(request, new PortResolverImpl()));
JSONAssert.assertEquals(REQUEST_JSON, actualString, true); JSONAssert.assertEquals(REQUEST_JSON, actualString, true);
} }
@ -106,13 +106,13 @@ public class DefaultSavedRequestMixinTests extends AbstractMixinTests {
.setScheme("http").setRequestURL("http://localhost").setServerName("localhost").setRequestURI("") .setScheme("http").setRequestURL("http://localhost").setServerName("localhost").setRequestURI("")
.setLocales(Collections.singletonList(new Locale("en"))).setContextPath("").setMethod("") .setLocales(Collections.singletonList(new Locale("en"))).setContextPath("").setMethod("")
.setServletPath("").build(); .setServletPath("").build();
String actualString = buildObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(request); String actualString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request);
JSONAssert.assertEquals(REQUEST_JSON, actualString, true); JSONAssert.assertEquals(REQUEST_JSON, actualString, true);
} }
@Test @Test
public void deserializeDefaultSavedRequest() throws IOException { public void deserializeDefaultSavedRequest() throws IOException {
DefaultSavedRequest request = (DefaultSavedRequest) buildObjectMapper().readValue(REQUEST_JSON, Object.class); DefaultSavedRequest request = (DefaultSavedRequest) mapper.readValue(REQUEST_JSON, Object.class);
assertThat(request).isNotNull(); assertThat(request).isNotNull();
assertThat(request.getCookies()).hasSize(1); assertThat(request.getCookies()).hasSize(1);
assertThat(request.getLocales()).hasSize(1).contains(new Locale("en")); assertThat(request.getLocales()).hasSize(1).contains(new Locale("en"));

View File

@ -25,7 +25,6 @@ import javax.servlet.http.Cookie;
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException; import org.json.JSONException;
import org.junit.Test; import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONAssert;
@ -61,14 +60,13 @@ public class SavedCookieMixinTests extends AbstractMixinTests {
@Test @Test
public void serializeWithDefaultConfigurationTest() throws JsonProcessingException, JSONException { public void serializeWithDefaultConfigurationTest() throws JsonProcessingException, JSONException {
SavedCookie savedCookie = new SavedCookie(new Cookie("SESSION", "123456789")); SavedCookie savedCookie = new SavedCookie(new Cookie("SESSION", "123456789"));
String actualJson = buildObjectMapper().writeValueAsString(savedCookie); String actualJson = mapper.writeValueAsString(savedCookie);
JSONAssert.assertEquals(COOKIE_JSON, actualJson, true); JSONAssert.assertEquals(COOKIE_JSON, actualJson, true);
} }
@Test @Test
public void serializeWithOverrideConfigurationTest() throws JsonProcessingException, JSONException { public void serializeWithOverrideConfigurationTest() throws JsonProcessingException, JSONException {
SavedCookie savedCookie = new SavedCookie(new Cookie("SESSION", "123456789")); SavedCookie savedCookie = new SavedCookie(new Cookie("SESSION", "123456789"));
ObjectMapper mapper = buildObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PUBLIC_ONLY) mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PUBLIC_ONLY)
.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.ANY); .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.ANY);
String actualJson = mapper.writeValueAsString(savedCookie); String actualJson = mapper.writeValueAsString(savedCookie);
@ -79,14 +77,14 @@ public class SavedCookieMixinTests extends AbstractMixinTests {
public void serializeSavedCookieWithList() throws JsonProcessingException, JSONException { public void serializeSavedCookieWithList() throws JsonProcessingException, JSONException {
List<SavedCookie> savedCookies = new ArrayList<SavedCookie>(); List<SavedCookie> savedCookies = new ArrayList<SavedCookie>();
savedCookies.add(new SavedCookie(new Cookie("SESSION", "123456789"))); savedCookies.add(new SavedCookie(new Cookie("SESSION", "123456789")));
String actualJson = buildObjectMapper().writeValueAsString(savedCookies); String actualJson = mapper.writeValueAsString(savedCookies);
JSONAssert.assertEquals(COOKIES_JSON, actualJson, true); JSONAssert.assertEquals(COOKIES_JSON, actualJson, true);
} }
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void deserializeSavedCookieWithList() throws IOException, JSONException { public void deserializeSavedCookieWithList() throws IOException, JSONException {
List<SavedCookie> savedCookies = (List<SavedCookie>)buildObjectMapper().readValue(COOKIES_JSON, Object.class); List<SavedCookie> savedCookies = (List<SavedCookie>)mapper.readValue(COOKIES_JSON, Object.class);
assertThat(savedCookies).isNotNull().hasSize(1); assertThat(savedCookies).isNotNull().hasSize(1);
assertThat(savedCookies.get(0).getName()).isEqualTo("SESSION"); assertThat(savedCookies.get(0).getName()).isEqualTo("SESSION");
assertThat(savedCookies.get(0).getValue()).isEqualTo("123456789"); assertThat(savedCookies.get(0).getValue()).isEqualTo("123456789");
@ -94,7 +92,7 @@ public class SavedCookieMixinTests extends AbstractMixinTests {
@Test @Test
public void deserializeSavedCookieJsonTest() throws IOException { public void deserializeSavedCookieJsonTest() throws IOException {
SavedCookie savedCookie = (SavedCookie) buildObjectMapper().readValue(COOKIE_JSON, Object.class); SavedCookie savedCookie = (SavedCookie) mapper.readValue(COOKIE_JSON, Object.class);
assertThat(savedCookie).isNotNull(); assertThat(savedCookie).isNotNull();
assertThat(savedCookie.getName()).isEqualTo("SESSION"); assertThat(savedCookie.getName()).isEqualTo("SESSION");
assertThat(savedCookie.getValue()).isEqualTo("123456789"); assertThat(savedCookie.getValue()).isEqualTo("123456789");

View File

@ -19,15 +19,12 @@ package org.springframework.security.web.jackson2;
import java.io.IOException; import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONException; import org.json.JSONException;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession; import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.jackson2.SecurityJacksonModules;
import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.authentication.WebAuthenticationDetails;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -36,10 +33,8 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Jitendra Singh * @author Jitendra Singh
* @since 4.2 * @since 4.2
*/ */
public class WebAuthenticationDetailsMixinTests { public class WebAuthenticationDetailsMixinTests extends AbstractMixinTests {
ObjectMapper mapper;
// @formatter:off // @formatter:off
private static final String AUTHENTICATION_DETAILS_JSON = "{" private static final String AUTHENTICATION_DETAILS_JSON = "{"
+ "\"@class\": \"org.springframework.security.web.authentication.WebAuthenticationDetails\"," + "\"@class\": \"org.springframework.security.web.authentication.WebAuthenticationDetails\","
@ -49,13 +44,6 @@ public class WebAuthenticationDetailsMixinTests {
+ "}"; + "}";
// @formatter:on // @formatter:on
@Before
public void setup() {
this.mapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader();
this.mapper.registerModules(SecurityJacksonModules.getModules(loader));
}
@Test @Test
public void buildWebAuthenticationDetailsUsingDifferentConstructors() public void buildWebAuthenticationDetailsUsingDifferentConstructors()
throws IOException { throws IOException {
@ -65,7 +53,7 @@ public class WebAuthenticationDetailsMixinTests {
WebAuthenticationDetails details = new WebAuthenticationDetails(request); WebAuthenticationDetails details = new WebAuthenticationDetails(request);
WebAuthenticationDetails authenticationDetails = this.mapper.readValue(AUTHENTICATION_DETAILS_JSON, WebAuthenticationDetails authenticationDetails = mapper.readValue(AUTHENTICATION_DETAILS_JSON,
WebAuthenticationDetails.class); WebAuthenticationDetails.class);
assertThat(details.equals(authenticationDetails)); assertThat(details.equals(authenticationDetails));
} }
@ -77,14 +65,14 @@ public class WebAuthenticationDetailsMixinTests {
request.setRemoteAddr("/localhost"); request.setRemoteAddr("/localhost");
request.setSession(new MockHttpSession(null, "1")); request.setSession(new MockHttpSession(null, "1"));
WebAuthenticationDetails details = new WebAuthenticationDetails(request); WebAuthenticationDetails details = new WebAuthenticationDetails(request);
String actualJson = this.mapper.writeValueAsString(details); String actualJson = mapper.writeValueAsString(details);
JSONAssert.assertEquals(AUTHENTICATION_DETAILS_JSON, actualJson, true); JSONAssert.assertEquals(AUTHENTICATION_DETAILS_JSON, actualJson, true);
} }
@Test @Test
public void webAuthenticationDetailsDeserializeTest() public void webAuthenticationDetailsDeserializeTest()
throws IOException, JSONException { throws IOException, JSONException {
WebAuthenticationDetails details = this.mapper.readValue(AUTHENTICATION_DETAILS_JSON, WebAuthenticationDetails details = mapper.readValue(AUTHENTICATION_DETAILS_JSON,
WebAuthenticationDetails.class); WebAuthenticationDetails.class);
assertThat(details).isNotNull(); assertThat(details).isNotNull();
assertThat(details.getRemoteAddress()).isEqualTo("/localhost"); assertThat(details.getRemoteAddress()).isEqualTo("/localhost");