Add JSON Serialization
Fixes gh-3812
This commit is contained in:
committed by
Rob Winch
parent
4d02a5c0a0
commit
d77ca17e95
+3
-4
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
+31
-10
@@ -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;
|
||||
|
||||
+19
-4
@@ -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
|
||||
// ========================================================================================================
|
||||
|
||||
|
||||
+59
@@ -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) {
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+66
@@ -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) {
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+56
@@ -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();
|
||||
}
|
||||
@@ -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) {}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
}
|
||||
+85
@@ -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();
|
||||
}
|
||||
}
|
||||
+48
@@ -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 {
|
||||
}
|
||||
@@ -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.
|
||||
*/
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* 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.databind.ObjectMapper;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
/**
|
||||
* @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;
|
||||
}
|
||||
|
||||
User createDefaultUser() {
|
||||
return createUser("dummy", "password", "ROLE_USER");
|
||||
}
|
||||
|
||||
User createUser(String username, String password, String authority) {
|
||||
return new User(username, password, Collections.singletonList(new SimpleGrantedAuthority(authority)));
|
||||
}
|
||||
}
|
||||
+95
@@ -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.jackson2;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import org.json.JSONException;
|
||||
import org.junit.Test;
|
||||
import org.skyscreamer.jsonassert.JSONAssert;
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
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.Collections;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Jitendra Singh
|
||||
* @since 4.2
|
||||
*/
|
||||
public class AnonymousAuthenticationTokenMixinTests extends AbstractMixinTests {
|
||||
|
||||
String hashKey = "key";
|
||||
String anonymousAuthTokenJson = "{\"@class\": \"org.springframework.security.authentication.AnonymousAuthenticationToken\", \"details\": null," +
|
||||
"\"principal\": {\"@class\": \"org.springframework.security.core.userdetails.User\", \"username\": \"dummy\", \"password\": %s," +
|
||||
" \"accountNonExpired\": true, \"enabled\": true, " +
|
||||
"\"accountNonLocked\": true, \"credentialsNonExpired\": true, \"authorities\": [\"java.util.Collections$UnmodifiableSet\"," +
|
||||
"[{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}, \"authenticated\": true, \"keyHash\": " + hashKey.hashCode() + "," +
|
||||
"\"authorities\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testWithNullAuthorities() throws JsonProcessingException, JSONException {
|
||||
new AnonymousAuthenticationToken("key", "principal", null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testWithEmptyAuthorities() throws JsonProcessingException, JSONException {
|
||||
new AnonymousAuthenticationToken("key", "principal", Collections.<GrantedAuthority>emptyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serializeAnonymousAuthenticationTokenTest() throws JsonProcessingException, JSONException {
|
||||
User user = createDefaultUser();
|
||||
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(
|
||||
hashKey, user, user.getAuthorities()
|
||||
);
|
||||
String actualJson = buildObjectMapper().writeValueAsString(token);
|
||||
JSONAssert.assertEquals(String.format(anonymousAuthTokenJson, "\"password\""), actualJson, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deserializeAnonymousAuthenticationTokenTest() throws IOException {
|
||||
AnonymousAuthenticationToken token = buildObjectMapper()
|
||||
.readValue(String.format(anonymousAuthTokenJson,"\"password\""), AnonymousAuthenticationToken.class);
|
||||
assertThat(token).isNotNull();
|
||||
assertThat(token.getKeyHash()).isEqualTo(hashKey.hashCode());
|
||||
assertThat(token.getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
}
|
||||
|
||||
@Test(expected = JsonMappingException.class)
|
||||
public void deserializeAnonymousAuthenticationTokenWithoutAuthoritiesTest() throws IOException {
|
||||
String jsonString = "{\"@class\": \"org.springframework.security.authentication.AnonymousAuthenticationToken\", \"details\": null," +
|
||||
"\"principal\": \"user\", \"authenticated\": true, \"keyHash\": " + hashKey.hashCode() + "," +
|
||||
"\"authorities\": [\"java.util.ArrayList\", []]}";
|
||||
buildObjectMapper().readValue(jsonString, AnonymousAuthenticationToken.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serializeAnonymousAuthenticationTokenMixinAfterEraseCredentialTest() throws JsonProcessingException, JSONException {
|
||||
User user = createDefaultUser();
|
||||
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(
|
||||
hashKey, user, user.getAuthorities()
|
||||
);
|
||||
token.eraseCredentials();
|
||||
String actualJson = buildObjectMapper().writeValueAsString(token);
|
||||
JSONAssert.assertEquals(String.format(anonymousAuthTokenJson, "null"), actualJson, true);
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* 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.JsonProcessingException;
|
||||
import org.json.JSONException;
|
||||
import org.junit.Test;
|
||||
import org.skyscreamer.jsonassert.JSONAssert;
|
||||
import org.springframework.security.authentication.RememberMeAuthenticationToken;
|
||||
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.Collections;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Jitendra Singh
|
||||
* @since 4.2
|
||||
*/
|
||||
public class RememberMeAuthenticationTokenMixinTests extends AbstractMixinTests {
|
||||
|
||||
String rememberMeKey = "rememberMe";
|
||||
String rememberMeAuthTokenJson = "{\"@class\": \"org.springframework.security.authentication.RememberMeAuthenticationToken\"," +
|
||||
"\"keyHash\": " + rememberMeKey.hashCode() + ", \"authenticated\": true, \"details\": null," +
|
||||
"\"principal\": {\"@class\": \"org.springframework.security.core.userdetails.User\", \"username\": \"dummy\", \"password\": %s," +
|
||||
" \"enabled\": true, \"accountNonExpired\": true, \"accountNonLocked\": true, \"credentialsNonExpired\": true, " +
|
||||
"\"authorities\": [\"java.util.Collections$UnmodifiableSet\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}," +
|
||||
"\"authorities\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
|
||||
|
||||
String rememberMeAuthTokenWithoutUserJson = "{\"@class\": \"org.springframework.security.authentication.RememberMeAuthenticationToken\"," +
|
||||
"\"keyHash\": " + rememberMeKey.hashCode() + ", \"authenticated\": true, \"details\": null," +
|
||||
"\"principal\": \"dummy\", \"authorities\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testWithNullPrincipal() throws JsonProcessingException, JSONException {
|
||||
new RememberMeAuthenticationToken("key", null, Collections.<GrantedAuthority>emptyList());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testWithNullKey() throws JsonProcessingException, JSONException {
|
||||
new RememberMeAuthenticationToken(null, "principal", Collections.<GrantedAuthority>emptyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serializeRememberMeAuthenticationToken() throws JsonProcessingException, JSONException {
|
||||
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(rememberMeKey, "dummy", Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")));
|
||||
String actualJson = buildObjectMapper().writeValueAsString(token);
|
||||
JSONAssert.assertEquals(rememberMeAuthTokenWithoutUserJson, actualJson, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serializeRememberMeAuthenticationWithUserToken() throws JsonProcessingException, JSONException {
|
||||
User user = createDefaultUser();
|
||||
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(rememberMeKey, user, user.getAuthorities());
|
||||
String actualJson = buildObjectMapper().writeValueAsString(token);
|
||||
JSONAssert.assertEquals(String.format(rememberMeAuthTokenJson, "\"password\""), actualJson, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serializeRememberMeAuthenticationWithUserTokenAfterEraseCredential() throws JsonProcessingException, JSONException {
|
||||
User user = createDefaultUser();
|
||||
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken(rememberMeKey, user, user.getAuthorities());
|
||||
token.eraseCredentials();
|
||||
String actualJson = buildObjectMapper().writeValueAsString(token);
|
||||
JSONAssert.assertEquals(String.format(rememberMeAuthTokenJson, "null"), actualJson, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deserializeRememberMeAuthenticationToken() throws IOException {
|
||||
RememberMeAuthenticationToken token = buildObjectMapper().readValue(rememberMeAuthTokenWithoutUserJson, RememberMeAuthenticationToken.class);
|
||||
assertThat(token).isNotNull();
|
||||
assertThat(token.getPrincipal()).isNotNull().isEqualTo("dummy").isEqualTo(token.getName());
|
||||
assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deserializeRememberMeAuthenticationTokenWithUserTest() throws IOException {
|
||||
RememberMeAuthenticationToken token = buildObjectMapper()
|
||||
.readValue(String.format(rememberMeAuthTokenJson, "\"password\""), RememberMeAuthenticationToken.class);
|
||||
assertThat(token).isNotNull();
|
||||
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
|
||||
assertThat(((User)token.getPrincipal()).getUsername()).isEqualTo("dummy");
|
||||
assertThat(((User)token.getPrincipal()).getPassword()).isEqualTo("password");
|
||||
assertThat(((User) token.getPrincipal()).getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
assertThat(((User) token.getPrincipal()).isEnabled()).isEqualTo(true);
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* 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.JsonProcessingException;
|
||||
import org.json.JSONException;
|
||||
import org.junit.Test;
|
||||
import org.skyscreamer.jsonassert.JSONAssert;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextImpl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Jitendra Singh
|
||||
* @since 4.2
|
||||
*/
|
||||
public class SecurityContextMixinTests extends AbstractMixinTests {
|
||||
|
||||
String securityContextJson = "{\"@class\": \"org.springframework.security.core.context.SecurityContextImpl\", \"authentication\": " +
|
||||
"{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\"," +
|
||||
"\"principal\": \"dummy\", \"credentials\": \"password\", \"authenticated\": true, \"details\": null," +
|
||||
"\"authorities\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]" +
|
||||
"}" +
|
||||
"}";
|
||||
|
||||
@Test
|
||||
public void securityContextSerializeTest() throws JsonProcessingException, JSONException {
|
||||
SecurityContext context = new SecurityContextImpl();
|
||||
context.setAuthentication(new UsernamePasswordAuthenticationToken("dummy", "password", Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"))));
|
||||
String actualJson = buildObjectMapper().writeValueAsString(context);
|
||||
JSONAssert.assertEquals(securityContextJson, actualJson, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void securityContextDeserializeTest() throws IOException {
|
||||
SecurityContext context = buildObjectMapper().readValue(securityContextJson, SecurityContextImpl.class);
|
||||
assertThat(context).isNotNull();
|
||||
assertThat(context.getAuthentication()).isNotNull().isInstanceOf(UsernamePasswordAuthenticationToken.class);
|
||||
assertThat(context.getAuthentication().getPrincipal()).isEqualTo("dummy");
|
||||
assertThat(context.getAuthentication().getCredentials()).isEqualTo("password");
|
||||
assertThat(context.getAuthentication().isAuthenticated()).isEqualTo(true);
|
||||
assertThat(context.getAuthentication().getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
}
|
||||
}
|
||||
+61
@@ -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.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.core.authority.SimpleGrantedAuthority;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* @author Jitendra Singh
|
||||
* @since 4.2
|
||||
*/
|
||||
public class SimpleGrantedAuthorityMixinTests extends AbstractMixinTests {
|
||||
|
||||
String simpleGrantedAuthorityJson = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}";
|
||||
|
||||
@Test
|
||||
public void serializeSimpleGrantedAuthorityTest() throws JsonProcessingException, JSONException {
|
||||
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
|
||||
String serializeJson = buildObjectMapper().writeValueAsString(authority);
|
||||
JSONAssert.assertEquals(simpleGrantedAuthorityJson, serializeJson, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deserializeGrantedAuthorityTest() throws IOException {
|
||||
SimpleGrantedAuthority authority = buildObjectMapper().readValue(simpleGrantedAuthorityJson, SimpleGrantedAuthority.class);
|
||||
assertThat(authority).isNotNull();
|
||||
assertThat(authority.getAuthority()).isNotNull().isEqualTo("ROLE_USER");
|
||||
}
|
||||
|
||||
@Test(expected = JsonMappingException.class)
|
||||
public void deserializeGrantedAuthorityWithoutRoleTest() throws IOException {
|
||||
String json = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\"}";
|
||||
buildObjectMapper().readValue(json, SimpleGrantedAuthority.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* 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.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.json.JSONException;
|
||||
import org.junit.Test;
|
||||
import org.skyscreamer.jsonassert.JSONAssert;
|
||||
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.Collections;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Jitendra Singh
|
||||
* @since 4.2
|
||||
*/
|
||||
public class UserDeserializerTests extends AbstractMixinTests {
|
||||
|
||||
String userWithAuthoritiesJson = "{\"@class\": \"org.springframework.security.core.userdetails.User\", \"username\": \"admin\"," +
|
||||
" \"password\": %s, \"accountNonExpired\": true, \"accountNonLocked\": true, \"credentialsNonExpired\": true, " +
|
||||
"\"enabled\": true, \"authorities\": [\"java.util.Collections$UnmodifiableSet\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
|
||||
|
||||
String userWithoutAuthoritiesJson = "{\"@class\": \"org.springframework.security.core.userdetails.User\", \"username\": \"admin\"," +
|
||||
" \"password\": \"1234\", \"accountNonExpired\": true, \"accountNonLocked\": true, \"credentialsNonExpired\": true," +
|
||||
" \"enabled\": true, \"authorities\": [\"java.util.Collections$UnmodifiableSet\", []]}";
|
||||
|
||||
@Test
|
||||
public void serializeUserTest() throws JsonProcessingException, JSONException {
|
||||
ObjectMapper mapper = buildObjectMapper();
|
||||
User user = new User("admin", "1234", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
|
||||
String userJson = mapper.writeValueAsString(user);
|
||||
JSONAssert.assertEquals(String.format(userWithAuthoritiesJson, "\"1234\""), userJson, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serializeUserWithoutAuthority() throws JsonProcessingException, JSONException {
|
||||
ObjectMapper mapper = buildObjectMapper();
|
||||
User user = new User("admin", "1234", Collections.<GrantedAuthority>emptyList());
|
||||
String userJson = mapper.writeValueAsString(user);
|
||||
JSONAssert.assertEquals(userWithoutAuthoritiesJson, userJson, true);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void deserializeUserWithNullPasswordEmptyAuthorityTest() throws IOException {
|
||||
String userJsonWithoutPasswordString = "{\"@class\": \"org.springframework.security.core.userdetails.User\", " +
|
||||
"\"username\": \"user\", \"accountNonExpired\": true, " +
|
||||
"\"accountNonLocked\": true, \"credentialsNonExpired\": true, \"enabled\": true, " +
|
||||
"\"authorities\": []}";
|
||||
ObjectMapper mapper = buildObjectMapper();
|
||||
mapper.readValue(userJsonWithoutPasswordString, User.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deserializeUserWithNullPasswordNoAuthorityTest() throws IOException {
|
||||
String userJsonWithoutPasswordString = "{\"@class\": \"org.springframework.security.core.userdetails.User\", " +
|
||||
"\"username\": \"admin\", \"accountNonExpired\": true, " +
|
||||
"\"accountNonLocked\": true, \"credentialsNonExpired\": true, \"enabled\": true, " +
|
||||
"\"authorities\": [\"java.util.HashSet\", []]}";
|
||||
ObjectMapper mapper = buildObjectMapper();
|
||||
User user = mapper.readValue(userJsonWithoutPasswordString, User.class);
|
||||
assertThat(user).isNotNull();
|
||||
assertThat(user.getUsername()).isEqualTo("admin");
|
||||
assertThat(user.getPassword()).isEqualTo("");
|
||||
assertThat(user.getAuthorities()).hasSize(0);
|
||||
assertThat(user.isEnabled()).isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void deserializeUserWithNoClassIdInAuthoritiesTest() throws IOException {
|
||||
String userJson = "{\"@class\": \"org.springframework.security.core.userdetails.User\", " +
|
||||
"\"username\": \"user\", \"password\": \"pass\", \"accountNonExpired\": false, " +
|
||||
"\"accountNonLocked\": false, \"credentialsNonExpired\": false, \"enabled\": false, " +
|
||||
"\"authorities\": [{\"role\": \"ROLE_USER\"}]}";
|
||||
buildObjectMapper().readValue(userJson, User.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deserializeUserWithClassIdInAuthoritiesTest() throws IOException {
|
||||
User user = buildObjectMapper().readValue(String.format(userWithAuthoritiesJson, "\"1234\""), User.class);
|
||||
assertThat(user).isNotNull();
|
||||
assertThat(user.getUsername()).isEqualTo("admin");
|
||||
assertThat(user.getPassword()).isEqualTo("1234");
|
||||
assertThat(user.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* 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.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.json.JSONException;
|
||||
import org.junit.Test;
|
||||
import org.skyscreamer.jsonassert.JSONAssert;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
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.Collections;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* @author Jitendra Singh
|
||||
* @since 4.2
|
||||
*/
|
||||
public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixinTests {
|
||||
|
||||
String unauthenticatedTokenWithoutUserPrincipal = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\"," +
|
||||
" \"principal\": \"user1\", \"credentials\": \"password\", \"authenticated\": false, \"details\": null, " +
|
||||
"\"authorities\": [\"java.util.ArrayList\", []]}";
|
||||
|
||||
String authenticatedTokenWithoutUserPrincipal = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\"," +
|
||||
" \"principal\": \"user1\", \"credentials\": \"password\", \"authenticated\": true, \"details\": null, " +
|
||||
"\"authorities\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
|
||||
|
||||
String authenticatedTokenWithUserPrincipal = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\"," +
|
||||
"\"principal\": {\"@class\": \"org.springframework.security.core.userdetails.User\", \"username\": \"user\", \"password\": %s, \"accountNonExpired\": true, \"enabled\": true, " +
|
||||
"\"accountNonLocked\": true, \"credentialsNonExpired\": true, \"authorities\": [\"java.util.Collections$UnmodifiableSet\"," +
|
||||
"[{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}, \"credentials\": %s," +
|
||||
"\"details\": null, \"authenticated\": true," +
|
||||
"\"authorities\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
|
||||
|
||||
@Test
|
||||
public void serializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws JsonProcessingException, JSONException {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user1", "password");
|
||||
String serializedJson = buildObjectMapper().writeValueAsString(token);
|
||||
JSONAssert.assertEquals(unauthenticatedTokenWithoutUserPrincipal, serializedJson, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws JsonProcessingException, JSONException {
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user1", "password", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
|
||||
String serializedJson = buildObjectMapper().writeValueAsString(token);
|
||||
JSONAssert.assertEquals(authenticatedTokenWithoutUserPrincipal, serializedJson, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deserializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException, JSONException {
|
||||
UsernamePasswordAuthenticationToken token = buildObjectMapper()
|
||||
.readValue(unauthenticatedTokenWithoutUserPrincipal, UsernamePasswordAuthenticationToken.class);
|
||||
assertThat(token).isNotNull();
|
||||
assertThat(token.isAuthenticated()).isEqualTo(false);
|
||||
assertThat(token.getAuthorities()).isNotNull().hasSize(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException {
|
||||
UsernamePasswordAuthenticationToken token = buildObjectMapper()
|
||||
.readValue(authenticatedTokenWithoutUserPrincipal, UsernamePasswordAuthenticationToken.class);
|
||||
assertThat(token).isNotNull();
|
||||
assertThat(token.isAuthenticated()).isEqualTo(true);
|
||||
assertThat(token.getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinWithUserTest() throws JsonProcessingException, JSONException {
|
||||
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
|
||||
User user = new User("user", "password", Collections.singleton(authority));
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, "password", Collections.singleton(authority));
|
||||
String actualJson = buildObjectMapper().writeValueAsString(token);
|
||||
JSONAssert.assertEquals(String.format(authenticatedTokenWithUserPrincipal, "password", "password"), actualJson, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithUserTest() throws IOException {
|
||||
ObjectMapper mapper = buildObjectMapper();
|
||||
UsernamePasswordAuthenticationToken token = mapper
|
||||
.readValue(String.format(authenticatedTokenWithUserPrincipal, "\"password\"", "\"password\""), UsernamePasswordAuthenticationToken.class);
|
||||
assertThat(token).isNotNull();
|
||||
assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
|
||||
assertThat(((User)token.getPrincipal()).getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
assertThat(token.isAuthenticated()).isEqualTo(true);
|
||||
assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinAfterEraseCredentialInvoked() throws JsonProcessingException, JSONException {
|
||||
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
|
||||
User user = new User("user", "password", Collections.singleton(authority));
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, "password", Collections.singleton(authority));
|
||||
token.eraseCredentials();
|
||||
String actualJson = buildObjectMapper().writeValueAsString(token);
|
||||
JSONAssert.assertEquals(String.format(authenticatedTokenWithUserPrincipal, "null", "null"), actualJson, true);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user