Spring Security session object serialization with SecurityJackson2Modules
Asked Answered
E

0

0

I'm using Spring Security with Spring Session which serializes the session to Redis as JSON. To make it properly working I make this Spring Session configuration. Also, I added SecurityJackson2Modules to the Redis Jackson serializer to make it working properly with Spring Security object.

How I understand any class serialized to session with Spring Security should be marked with an annotation like @JsonTypeInfo or @JsonSerialize if it's not in the allowed classes list of SecurityJackson2Modules. Classes like Date, ArrayList or Instant are there but BigDecimal is not for some reason.

How could I resolve the problem properly? Honestly I have a solution but I'm not sure if it's the most optimal.

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
public class ProductDto {

    private Long id;

    private String name;

    private String description;

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "type")
    @JsonSubTypes({ @JsonSubTypes.Type(name = "BIG_DECIMAL", value = BigDecimal.class) })
    private BigDecimal price;

    // getters, setters etc.

}

UPD. Added an issue https://github.com/spring-projects/spring-security/issues/10325

Eal answered 26/9, 2021 at 19:31 Comment(5)
Why do you think that product and especially price should be part of security context?Apocalypse
Those limitations are not only about SecurityContext. They are about all the classes I want to store in the session. BTW. I already had a discussion about that at Spring Security GitHubEal
1) You should you proper tools for your goal. The SecurityJackson2Modules is intended to support serialization of security related objects only, like authentication tokens and user info. Anything else has nothing to do with SecurityJackson2Modules. 2) Spring can serialize any objects in the session, but by default it uses JDK serialization. 3) If you want to serialize any objects in the Spring session in JSON format, you should configure ObjectMapper correspondingly. If you wish, you can even implement your own module for this...Apocalypse
... But is it not correct to expect that SecurityJackson2Modules will fit any non-security goals.Apocalypse
I have commented the issue at Spring Security GitHub.Apocalypse

© 2022 - 2025 — McMap. All rights reserved.