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

@@ -40,8 +40,8 @@ public abstract class AbstractAuthenticationToken implements Authentication,
// ~ Instance fields
// ================================================================================================
private Object details;
private final Collection<GrantedAuthority> authorities;
private Object details;
private boolean authenticated = false;
// ~ Constructors
@@ -51,7 +51,7 @@ public abstract class AbstractAuthenticationToken implements Authentication,
* Creates a token with the supplied array of authorities.
*
* @param authorities the collection of <tt>GrantedAuthority</tt>s for the principal
* represented by this authentication object.
* represented by this authentication object.
*/
public AbstractAuthenticationToken(Collection<? extends GrantedAuthority> authorities) {
if (authorities == null) {
@@ -215,8 +215,7 @@ public abstract class AbstractAuthenticationToken implements Authentication,
sb.append(authority);
}
}
else {
} else {
sb.append("Not granted any authorities");
}

View File

@@ -41,24 +41,33 @@ public class AnonymousAuthenticationToken extends AbstractAuthenticationToken im
/**
* Constructor.
*
* @param key to identify if this object made by an authorised client
* @param principal the principal (typically a <code>UserDetails</code>)
* @param key to identify if this object made by an authorised client
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
*
* @throws IllegalArgumentException if a <code>null</code> was passed
*/
public AnonymousAuthenticationToken(String key, Object principal,
Collection<? extends GrantedAuthority> authorities) {
Collection<? extends GrantedAuthority> authorities) {
this(extractKeyHash(key), nullSafeValue(principal), authorities);
}
/**
* Constructor helps in Jackson Deserialization
*
* @param keyHash hashCode of provided Key, constructed by above constructor
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
* @since 4.2
*/
private AnonymousAuthenticationToken(Integer keyHash, Object principal,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
if ((key == null) || ("".equals(key)) || (principal == null)
|| "".equals(principal) || (authorities == null)
|| (authorities.isEmpty())) {
throw new IllegalArgumentException(
"Cannot pass null or empty values to constructor");
if (authorities == null || authorities.isEmpty()) {
throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
}
this.keyHash = key.hashCode();
this.keyHash = keyHash;
this.principal = principal;
setAuthenticated(true);
}
@@ -66,6 +75,18 @@ public class AnonymousAuthenticationToken extends AbstractAuthenticationToken im
// ~ Methods
// ========================================================================================================
private static Integer extractKeyHash(String key) {
Object value = nullSafeValue(key);
return value.hashCode();
}
private static Object nullSafeValue(Object value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
}
return value;
}
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;

View File

@@ -46,14 +46,13 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken {
/**
* Constructor.
*
* @param key to identify if this object made by an authorised client
* @param principal the principal (typically a <code>UserDetails</code>)
* @param key to identify if this object made by an authorised client
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
*
* @throws IllegalArgumentException if a <code>null</code> was passed
*/
public RememberMeAuthenticationToken(String key, Object principal,
Collection<? extends GrantedAuthority> authorities) {
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
if ((key == null) || ("".equals(key)) || (principal == null)
@@ -67,6 +66,22 @@ public class RememberMeAuthenticationToken extends AbstractAuthenticationToken {
setAuthenticated(true);
}
/**
* Private Constructor to help in Jackson deserialization.
*
* @param keyHash hashCode of above given key.
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
* @since 4.2
*/
private RememberMeAuthenticationToken(Integer keyHash, Object principal, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.keyHash = keyHash;
this.principal = principal;
setAuthenticated(true);
}
// ~ Methods
// ========================================================================================================

View File

@@ -0,0 +1,59 @@
/*
* 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.jackson2;
import com.fasterxml.jackson.annotation.*;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
/**
* This is a Jackson mixin class helps in serialize/deserialize
* {@link org.springframework.security.authentication.AnonymousAuthenticationToken} class. To use this class you need to register it
* with {@link com.fasterxml.jackson.databind.ObjectMapper} and {@link SimpleGrantedAuthorityMixin} because
* AnonymousAuthenticationToken contains SimpleGrantedAuthority.
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
*
* <i>Note: This class will save full class name into a property called @class</i>
*
* @author Jitendra Singh
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, isGetterVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.ANY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class AnonymousAuthenticationTokenMixin {
/**
* Constructor used by Jackson to create object of {@link org.springframework.security.authentication.AnonymousAuthenticationToken}.
*
* @param keyHash hashCode of key provided at the time of token creation by using
* {@link org.springframework.security.authentication.AnonymousAuthenticationToken#AnonymousAuthenticationToken(String, Object, Collection)}
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
*/
@JsonCreator
public AnonymousAuthenticationTokenMixin(@JsonProperty("keyHash") Integer keyHash, @JsonProperty("principal") Object principal,
@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities) {
}
}

View File

@@ -0,0 +1,63 @@
/*
* 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.jackson2;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collections;
/**
* Jackson module for spring-security-core. This module register {@link AnonymousAuthenticationTokenMixin},
* {@link RememberMeAuthenticationTokenMixin}, {@link SimpleGrantedAuthorityMixin}, {@link UnmodifiableSetMixin},
* {@link UserMixin} and {@link UsernamePasswordAuthenticationTokenMixin}. If no default typing enabled by default then
* it'll enable it because typing info is needed to properly serialize/deserialize objects. In order to use this module just
* add this module into your ObjectMapper configuration.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
* <b>Note: use {@link SecurityJacksonModules#getModules()} to get list of all security modules.</b>
*
* @author Jitendra Singh.
* @see SecurityJacksonModules
* @since 4.2
*/
public class CoreJackson2Module extends SimpleModule {
public CoreJackson2Module() {
super(CoreJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null));
}
@Override
public void setupModule(SetupContext context) {
SecurityJacksonModules.enableDefaultTyping((ObjectMapper) context.getOwner());
context.setMixInAnnotations(AnonymousAuthenticationToken.class, AnonymousAuthenticationTokenMixin.class);
context.setMixInAnnotations(RememberMeAuthenticationToken.class, RememberMeAuthenticationTokenMixin.class);
context.setMixInAnnotations(SimpleGrantedAuthority.class, SimpleGrantedAuthorityMixin.class);
context.setMixInAnnotations(Collections.unmodifiableSet(Collections.EMPTY_SET).getClass(), UnmodifiableSetMixin.class);
context.setMixInAnnotations(User.class, UserMixin.class);
context.setMixInAnnotations(UsernamePasswordAuthenticationToken.class, UsernamePasswordAuthenticationTokenMixin.class);
}
}

View File

@@ -0,0 +1,66 @@
/*
* 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.jackson2;
import com.fasterxml.jackson.annotation.*;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
/**
* This mixin class helps in serialize/deserialize
* {@link org.springframework.security.authentication.RememberMeAuthenticationToken} class. To use this class you need to register it
* with {@link com.fasterxml.jackson.databind.ObjectMapper} and 2 more mixin classes.
*
* <ol>
* <li>{@link SimpleGrantedAuthorityMixin}</li>
* <li>{@link UserMixin}</li>
* <li>{@link UnmodifiableSetMixin}</li>
* </ol>
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
*
* <i>Note: This class will save TypeInfo (full class name) into a property called @class</i>
*
* @author Jitendra Singh
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.ANY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class RememberMeAuthenticationTokenMixin {
/**
* Constructor used by Jackson to create
* {@link org.springframework.security.authentication.RememberMeAuthenticationToken} object.
*
* @param keyHash hashCode of above given key.
* @param principal the principal (typically a <code>UserDetails</code>)
* @param authorities the authorities granted to the principal
*/
@JsonCreator
public RememberMeAuthenticationTokenMixin(@JsonProperty("keyHash") Integer keyHash,
@JsonProperty("principal") Object principal,
@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities) {
}
}

View File

@@ -0,0 +1,106 @@
/*
* 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.jackson2;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* This utility class will find all the SecurityModules in classpath.
*
* <p>
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModules(SecurityJacksonModules.getModules());
* </pre>
* Above code is equivalent to
* <p>
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
* mapper.registerModule(new CoreJackson2Module());
* mapper.registerModule(new CasJackson2Module());
* mapper.registerModule(new WebJackson2Module());
* </pre>
*
* @author Jitendra Singh.
* @since 4.2
*/
public final class SecurityJacksonModules {
private static final Log logger = LogFactory.getLog(SecurityJacksonModules.class);
private static final List<String> securityJackson2ModuleClasses = Arrays.asList(
"org.springframework.security.jackson2.CoreJackson2Module",
"org.springframework.security.cas.jackson2.CasJackson2Module",
"org.springframework.security.web.jackson2.WebJackson2Module"
);
private SecurityJacksonModules() {
}
public static void enableDefaultTyping(ObjectMapper mapper) {
if(!ObjectUtils.isEmpty(mapper)) {
TypeResolverBuilder<?> typeBuilder = mapper.getDeserializationConfig().getDefaultTyper(null);
if (ObjectUtils.isEmpty(typeBuilder)) {
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
}
}
}
private static Module loadAndGetInstance(String className) {
Module instance = null;
try {
logger.debug("Loading module " + className);
Class<? extends Module> securityModule = (Class<? extends Module>) ClassUtils.forName(className, ClassUtils.getDefaultClassLoader());
if (!ObjectUtils.isEmpty(securityModule)) {
logger.debug("Loaded module " + className + ", now registering");
instance = securityModule.newInstance();
}
} catch (ClassNotFoundException e) {
logger.warn("Module class not found : " + e.getMessage());
} catch (InstantiationException e) {
logger.error(e.getMessage());
} catch (IllegalAccessException e) {
logger.error(e.getMessage());
}
return instance;
}
/**
* @return List of available security modules in classpath.
*/
public static List<Module> getModules() {
List<Module> modules = new ArrayList<Module>();
for (String className : securityJackson2ModuleClasses) {
Module module = loadAndGetInstance(className);
if (!ObjectUtils.isEmpty(module)) {
modules.add(module);
}
}
return modules;
}
}

View File

@@ -0,0 +1,56 @@
/*
* 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.jackson2;
import com.fasterxml.jackson.annotation.*;
/**
* Jackson Mixin class helps in serialize/deserialize
* {@link org.springframework.security.core.authority.SimpleGrantedAuthority}.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
* @author Jitendra Singh
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class SimpleGrantedAuthorityMixin {
/**
* Mixin Constructor.
* @param role
*/
@JsonCreator
public SimpleGrantedAuthorityMixin(@JsonProperty("role") String role) {
}
/**
* This method will ensure that getAuthority() doesn't serialized to <b>authority</b> key, it will be serialized
* as <b>role</b> key. Because above mixin constructor will look for role key to properly deserialize.
*
* @return
*/
@JsonProperty("role")
public abstract String getAuthority();
}

View File

@@ -0,0 +1,47 @@
/*
* 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.jackson2;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.util.Set;
/**
* This mixin class used to deserialize java.util.Collections$UnmodifiableSet and used with various AuthenticationToken
* implementation's mixin classes.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
*
* @author Jitendra Singh
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
public class UnmodifiableSetMixin {
/**
* Mixin Constructor
* @param s
*/
@JsonCreator
UnmodifiableSetMixin(Set s) {}
}

View File

@@ -0,0 +1,72 @@
/*
* 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.jackson2;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.io.IOException;
import java.util.Set;
/**
* Custom Deserializer for {@link User} class. This is already registered with {@link UserMixin}.
* You can also use it directly with your mixin class.
*
* @author Jitendra Singh
* @see UserMixin
* @since 4.2
*/
public class UserDeserializer extends JsonDeserializer<User> {
/**
* This method will create {@link User} object. It will ensure successful object creation even if password key is null in
* serialized json, because credentials may be removed from the {@link User} by invoking {@link User#eraseCredentials()}.
* In that case there won't be any password key in serialized json.
*
* @param jp
* @param ctxt
* @return
* @throws IOException
* @throws JsonProcessingException
*/
@Override
public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
JsonNode jsonNode = mapper.readTree(jp);
Set<GrantedAuthority> authorities = mapper.convertValue(jsonNode.get("authorities"), new TypeReference<Set<SimpleGrantedAuthority>>() {
});
return new User(
readJsonNode(jsonNode, "username").asText(), readJsonNode(jsonNode, "password").asText(""),
readJsonNode(jsonNode, "enabled").asBoolean(), readJsonNode(jsonNode, "accountNonExpired").asBoolean(),
readJsonNode(jsonNode, "credentialsNonExpired").asBoolean(),
readJsonNode(jsonNode, "accountNonLocked").asBoolean(), authorities
);
}
private JsonNode readJsonNode(JsonNode jsonNode, String field) {
return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance();
}
}

View File

@@ -0,0 +1,49 @@
/*
* 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.jackson2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* This mixin class helps in serialize/deserialize {@link org.springframework.security.core.userdetails.User}.
* This class also register a custom deserializer {@link UserDeserializer} to deserialize User object successfully.
* In order to use this mixin you need to register two more mixin classes in your ObjectMapper configuration.
* <ol>
* <li>{@link SimpleGrantedAuthorityMixin}</li>
* <li>{@link UnmodifiableSetMixin}</li>
* </ol>
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
*
* @author Jitendra Singh
* @see UserDeserializer
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonDeserialize(using = UserDeserializer.class)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class UserMixin {
}

View File

@@ -0,0 +1,85 @@
/*
* 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.jackson2;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.io.IOException;
import java.util.List;
/**
* Custom deserializer for {@link UsernamePasswordAuthenticationToken}. At the time of deserialization
* it will invoke suitable constructor depending on the value of <b>authenticated</b> property.
* It will ensure that the token's state must not change.
* <p>
* This deserializer is already registered with {@link UsernamePasswordAuthenticationTokenMixin} but
* you can also registered it with your own mixin class.
*
* @author Jitendra Singh
* @see UsernamePasswordAuthenticationTokenMixin
* @since 4.2
*/
public class UsernamePasswordAuthenticationTokenDeserializer extends JsonDeserializer<UsernamePasswordAuthenticationToken> {
/**
* This method construct {@link UsernamePasswordAuthenticationToken} object from serialized json.
* @param jp
* @param ctxt
* @return
* @throws IOException
* @throws JsonProcessingException
*/
@Override
public UsernamePasswordAuthenticationToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
UsernamePasswordAuthenticationToken token = null;
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
JsonNode jsonNode = mapper.readTree(jp);
Boolean authenticated = readJsonNode(jsonNode, "authenticated").asBoolean();
JsonNode principalNode = readJsonNode(jsonNode, "principal");
Object principal = null;
if(principalNode.isObject()) {
principal = mapper.readValue(principalNode.toString(), new TypeReference<User>() {});
} else {
principal = principalNode.asText();
}
Object credentials = readJsonNode(jsonNode, "credentials").asText();
List<GrantedAuthority> authorities = mapper.readValue(
readJsonNode(jsonNode, "authorities").toString(), new TypeReference<List<GrantedAuthority>>() {
});
if (authenticated) {
token = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
} else {
token = new UsernamePasswordAuthenticationToken(principal, credentials);
}
token.setDetails(readJsonNode(jsonNode, "details"));
return token;
}
private JsonNode readJsonNode(JsonNode jsonNode, String field) {
return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance();
}
}

View File

@@ -0,0 +1,48 @@
/*
* 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.jackson2;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/**
* This mixin class is used to serialize / deserialize
* {@link org.springframework.security.authentication.UsernamePasswordAuthenticationToken}. This class register
* a custom deserializer {@link UsernamePasswordAuthenticationTokenDeserializer}.
*
* In order to use this mixin you'll need to add 3 more mixin classes.
* <ol>
* <li>{@link UnmodifiableSetMixin}</li>
* <li>{@link SimpleGrantedAuthorityMixin}</li>
* <li>{@link UserMixin}</li>
* </ol>
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new CoreJackson2Module());
* </pre>
* @author Jitendra Singh
* @see CoreJackson2Module
* @see SecurityJacksonModules
* @since 4.2
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonDeserialize(using = UsernamePasswordAuthenticationTokenDeserializer.class)
public abstract class UsernamePasswordAuthenticationTokenMixin {
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright 2002-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.
*/
/**
* Mix-in classes to add Jackson serialization support.
*
* @author Jitendra Singh
* @since 4.2
*/
package org.springframework.security.jackson2;
/**
* Package contains Jackson mixin classes.
*/