spring-projects / spring-projects/spring-security

Spring Session integration do not supports primitive type as the principal

Open
#6,571 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

status: waiting-for-triage
Dominant language
Java
Stars
9.6k
Forks
6.3k
Avg merge
2d 11h
Merged PRs (30d)
52

Description

Summary

In a Spring Boot application using both Spring Security and Spring Session (with Redis and GenericJackson2JsonRedisSerializer), a UsernamePasswordAuthenticationToken with java.lang.Long(such as userId) as the principal can be serialized, but deserialized value is empty

Actual Behavior

deserialize value is empty string

Expected Behavior

the Long value as i stored

Configuration
@Configuration
public class SessionConfig implements BeanClassLoaderAware {

    private ClassLoader classLoader;

    @Bean
    public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
        return new GenericJackson2JsonRedisSerializer(objectMapper());
    }

    /**
     * Customized {@link ObjectMapper} to add mix-in for class that doesn't have default constructors
     *
     * {@link org.springframework.security.web.savedrequest.DefaultSavedRequest}
     *
     * @return
     */
    private ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModules(SecurityJackson2Modules.getModules(classLoader));
        return mapper;
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }
}
Version

Spring Boot: 2.1.0.RELEASE
Spring Security: 5.1.1.RELEASE
Spring Session: 2.1.1.RELEASE

Sample
private void test() {
	UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(1L, null, null);
	RedisOperationsSessionRepository sessionRepository = beanFactory.getBean(RedisOperationsSessionRepository.class);
	BoundHashOperations<Object, Object, Object> operations = sessionRepository.getSessionRedisOperations().boundHashOps("test");
	operations.put("sessionAttr:token", token);

	UsernamePasswordAuthenticationToken stored = (UsernamePasswordAuthenticationToken) operations.get("sessionAttr:token");
	System.out.println(stored);
}

The content stored in redis:

sessionAttr:token
{"@class":"org.springframework.security.authentication.UsernamePasswordAuthenticationToken","authorities":["java.util.Collections$EmptyList",[]],"details":null,"authenticated":true,"principal":["java.lang.Long",1],"credentials":null}

the deserialize object printed is:

org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ffffffc4: Principal: ; Credentials: [PROTECTED]; Authenticated: true; Details: null; Not granted any authorities

the magic is in UsernamePasswordAuthenticationTokenDeserializer's deserialize method:

@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.traverse(mapper), Object.class);
	} else {
		principal = principalNode.asText();
	}
	...
}

because the principal serialized is an array, the principalNode is a Jackson's ArrayNode, the asText() method return "".

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at UsernamePasswordAuthenticationTokenDeserializer.deserialize and reproduce the Redis session round trip from the sample with a Long principal. Inspect how the principal JsonNode is handled when it is serialized as an array; done means deserialization restores the stored Long value instead of an empty string.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, redis, spring, spring-boot
Domain
authentication, backend, security
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.