-
Notifications
You must be signed in to change notification settings - Fork 0
βοΈβπ₯ PMW-55: json sessie serialisatie βοΈβπ₯ #288
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,30 +6,46 @@ | |
|
|
||
| package nl.b3p.planmonitorwonen.api.configuration; | ||
|
|
||
| import java.io.InputStream; | ||
| import java.io.ObjectInputStream; | ||
| import com.fasterxml.jackson.annotation.JsonTypeInfo; | ||
| import java.lang.invoke.MethodHandles; | ||
| import java.nio.charset.StandardCharsets; | ||
| import javax.sql.DataSource; | ||
| import org.jspecify.annotations.NonNull; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import org.springframework.beans.factory.BeanClassLoaderAware; | ||
| import org.springframework.beans.factory.annotation.Qualifier; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.boot.jdbc.DataSourceBuilder; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.context.annotation.Profile; | ||
| import org.springframework.core.convert.ConversionFailedException; | ||
| import org.springframework.core.convert.ConversionService; | ||
| import org.springframework.core.convert.TypeDescriptor; | ||
| import org.springframework.core.convert.support.GenericConversionService; | ||
| import org.springframework.core.serializer.Deserializer; | ||
| import org.springframework.core.serializer.support.DeserializingConverter; | ||
| import org.springframework.core.serializer.support.SerializingConverter; | ||
| import org.springframework.jdbc.core.simple.JdbcClient; | ||
| import org.springframework.jdbc.datasource.DataSourceTransactionManager; | ||
| import org.springframework.security.jackson.SecurityJacksonModules; | ||
| import org.springframework.session.config.SessionRepositoryCustomizer; | ||
| import org.springframework.session.jdbc.JdbcIndexedSessionRepository; | ||
| import org.springframework.session.jdbc.config.annotation.SpringSessionDataSource; | ||
| import org.springframework.session.jdbc.config.annotation.web.http.EnableJdbcHttpSession; | ||
| import org.springframework.transaction.PlatformTransactionManager; | ||
| import tools.jackson.core.JacksonException; | ||
| import tools.jackson.core.StreamReadFeature; | ||
| import tools.jackson.databind.DefaultTyping; | ||
| import tools.jackson.databind.SerializationFeature; | ||
| import tools.jackson.databind.json.JsonMapper; | ||
| import tools.jackson.databind.jsontype.BasicPolymorphicTypeValidator; | ||
|
|
||
| @Configuration | ||
| @EnableJdbcHttpSession | ||
| @Profile("!test") | ||
| public class JdbcSessionConfiguration { | ||
| public class JdbcSessionConfiguration implements BeanClassLoaderAware { | ||
| private static final Logger logger = | ||
| LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); | ||
|
|
||
| @Value("${spring.datasource.url}") | ||
| private String dataSourceUrl; | ||
|
|
||
|
|
@@ -48,6 +64,27 @@ public class JdbcSessionConfiguration { | |
| @Value("${tailormap.datasource.password}") | ||
| private String sessionDataSourcePassword; | ||
|
|
||
| private static final String CREATE_SESSION_ATTRIBUTE_QUERY = | ||
| """ | ||
| INSERT INTO %TABLE_NAME%_ATTRIBUTES (SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) | ||
| VALUES (?, ?, convert_from(?, 'UTF8')::jsonb) | ||
| """; | ||
|
|
||
| private static final String UPDATE_SESSION_ATTRIBUTE_QUERY = | ||
| """ | ||
| UPDATE %TABLE_NAME%_ATTRIBUTES | ||
| SET ATTRIBUTE_BYTES = encode(?, 'escape')::jsonb | ||
| WHERE SESSION_PRIMARY_ID = ? | ||
| AND ATTRIBUTE_NAME = ? | ||
| """; | ||
|
|
||
| private ClassLoader classLoader; | ||
|
|
||
| @Override | ||
| public void setBeanClassLoader(@NonNull ClassLoader classLoader) { | ||
| this.classLoader = classLoader; | ||
| } | ||
|
|
||
| @Bean | ||
| public DataSource dataSource() { | ||
| DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create(); | ||
|
|
@@ -67,6 +104,14 @@ public JdbcClient tailormapJdbcClient(@Qualifier("tailormapDataSource") DataSour | |
| return JdbcClient.create(data); | ||
| } | ||
|
|
||
| @Bean | ||
| SessionRepositoryCustomizer<JdbcIndexedSessionRepository> customizer() { | ||
| return (sessionRepository) -> { | ||
| sessionRepository.setCreateSessionAttributeQuery(CREATE_SESSION_ATTRIBUTE_QUERY); | ||
| sessionRepository.setUpdateSessionAttributeQuery(UPDATE_SESSION_ATTRIBUTE_QUERY); | ||
| }; | ||
| } | ||
|
Comment on lines
+107
to
+113
|
||
|
|
||
| @Bean(name = {"springSessionDataSource", "tailormapDataSource"}) | ||
| @SpringSessionDataSource | ||
| public DataSource sessionDataSource() { | ||
|
|
@@ -85,20 +130,74 @@ public PlatformTransactionManager springSessionTransactionOperations( | |
|
|
||
mprins marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| @Bean("springSessionConversionService") | ||
| public ConversionService springSessionConversionService() { | ||
| GenericConversionService converter = new GenericConversionService(); | ||
| converter.addConverter(Object.class, byte[].class, new SerializingConverter()); | ||
| converter.addConverter(byte[].class, Object.class, new DeserializingConverter(new CustomDeserializer())); | ||
| return converter; | ||
| } | ||
| BasicPolymorphicTypeValidator.Builder builder = BasicPolymorphicTypeValidator.builder() | ||
| .allowIfSubType("org.tailormap.api.security.") | ||
| .allowIfSubType("org.springframework.security.") | ||
| .allowIfSubType("java.util.") | ||
| .allowIfSubType(java.lang.Number.class) | ||
| .allowIfSubType("java.time.") | ||
| .allowIfBaseType(Object.class); | ||
mprins marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| static class CustomDeserializer implements Deserializer<Object> { | ||
| @Override | ||
| public Object deserialize(InputStream inputStream) { | ||
| try (ObjectInputStream ois = new ObjectInputStream(inputStream)) { | ||
| return ois.readObject(); | ||
| } catch (Exception ignored) { | ||
| return null; | ||
| JsonMapper mapper = JsonMapper.builder() | ||
| .configure( | ||
| StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION, | ||
| (logger.isDebugEnabled() || logger.isTraceEnabled())) | ||
| .configure(SerializationFeature.INDENT_OUTPUT, (logger.isDebugEnabled() || logger.isTraceEnabled())) | ||
| .addMixIn( | ||
| org.tailormap.api.security.TailormapUserDetailsImpl.class, | ||
| org.tailormap.api.security.TailormapUserDetailsImplMixin.class) | ||
| .addMixIn( | ||
| org.tailormap.api.security.TailormapOidcUser.class, | ||
| org.tailormap.api.security.TailormapOidcUserMixin.class) | ||
| .addModules(SecurityJacksonModules.getModules(this.classLoader, builder)) | ||
| .activateDefaultTyping(builder.build(), DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY) | ||
| .build(); | ||
|
|
||
| final GenericConversionService converter = new GenericConversionService(); | ||
| // Object -> byte[] (serialize to JSON bytes) | ||
| // this is not actually done in the application because sessions are | ||
| // read-only, so this is commented out but left here for possible future use | ||
| // converter.addConverter(Object.class, byte[].class, source -> { | ||
| // try { | ||
| // logger.debug("Serializing Spring Session: {}", source); | ||
| // return mapper.writerFor(Object.class).writeValueAsBytes(source); | ||
| // } catch (JacksonException e) { | ||
| // logger.error("Error serializing Spring Session object: {}", source, e); | ||
| // throw new ConversionFailedException( | ||
| // TypeDescriptor.forObject(source), TypeDescriptor.valueOf(byte[].class), source, e); | ||
| // } | ||
| // }); | ||
| // byte[] -> Object (deserialize from JSON bytes) | ||
| converter.addConverter(byte[].class, Object.class, source -> { | ||
| try { | ||
| logger.debug( | ||
| "Deserializing Spring Session from bytes, length: {} ({})", | ||
| source.length, | ||
| new String(source, StandardCharsets.UTF_8)); | ||
| return mapper.readValue(source, Object.class); | ||
| } catch (JacksonException e) { | ||
| String preview; | ||
| try { | ||
| String content = new String(source, StandardCharsets.UTF_8); | ||
| int maxLength = 256; | ||
| if (logger.isDebugEnabled() || logger.isTraceEnabled()) { | ||
| preview = content; | ||
| } else { | ||
| preview = content.length() > maxLength ? content.substring(0, maxLength) + "..." : content; | ||
| } | ||
| } catch (Exception ex) { | ||
| preview = "<unavailable>"; | ||
| } | ||
| logger.error( | ||
| "Error deserializing Spring Session from bytes, length: {}, preview: {}", | ||
| source.length, | ||
| preview, | ||
| e); | ||
| throw new ConversionFailedException( | ||
| TypeDescriptor.valueOf(byte[].class), TypeDescriptor.valueOf(Object.class), source, e); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| return converter; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
src/main/java/org/tailormap/api/security/TailormapOidcUserMixin.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| /* | ||
| * Copyright (C) 2025 B3Partners B.V. | ||
| * | ||
| * SPDX-License-Identifier: MIT | ||
| */ | ||
| package org.tailormap.api.security; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonAutoDetect; | ||
| import com.fasterxml.jackson.annotation.JsonCreator; | ||
| import com.fasterxml.jackson.annotation.JsonIgnoreProperties; | ||
| import com.fasterxml.jackson.annotation.JsonProperty; | ||
| import com.fasterxml.jackson.annotation.JsonTypeInfo; | ||
| import java.util.Collection; | ||
| import java.util.Map; | ||
| import org.springframework.security.core.GrantedAuthority; | ||
|
|
||
| @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) | ||
| @JsonAutoDetect( | ||
| fieldVisibility = JsonAutoDetect.Visibility.ANY, | ||
| getterVisibility = JsonAutoDetect.Visibility.NONE, | ||
| isGetterVisibility = JsonAutoDetect.Visibility.NONE) | ||
| @JsonIgnoreProperties(ignoreUnknown = true) | ||
| public abstract class TailormapOidcUserMixin { | ||
|
|
||
| @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) | ||
| public TailormapOidcUserMixin( | ||
| @SuppressWarnings("unused") @JsonProperty("claims") Map<String, Object> claims, | ||
| @SuppressWarnings("unused") @JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities, | ||
| @SuppressWarnings("unused") @JsonProperty("attributes") Map<String, Object> attributes, | ||
| @SuppressWarnings("unused") @JsonProperty("nameAttributeKey") String nameAttributeKey, | ||
| @SuppressWarnings("unused") @JsonProperty("oidcRegistrationName") String oidcRegistrationName, | ||
| @SuppressWarnings("unused") @JsonProperty("additionalGroupProperties") | ||
| Collection<TailormapAdditionalProperty> additionalGroupProperties) { | ||
| // mixin constructor only for Jackson; no implementation | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.