I have a custom annotation for hide/show fields based on logged-in user roles.
I overrode the AnnotationIntrospector hasIgnoreMarker method to implement my logic.
This works only for the first logged-in user, and subsequent users inherent the first user permission even if they are not authorized to access first user fields. They basically see fields based on whoever the first logged-in user was.
I have tried to use request scope but got the same result.
Any guidance will be appreciated.
Custom annotation
@Documented
@Retention(RUNTIME)
@PreAuthorize("permitAll()")
@Inherited
public @interface RestrictFor {
String[] roles() default {};
}
Introspector
@Component
@RequiredArgsConstructor
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class JsonSerializerRestrictToIntrospector extends NopAnnotationIntrospector {
private final LoggedUserProvider loggedUserProvider;
@Override
public Version version() {
return PackageVersion.VERSION;
}
@Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
final RestrictFor annotation = m.getAnnotation(RestrictFor.class);
if (annotation != null && isNotBlank(List.of(annotation.roles()))) {
final Set<String> roles = new HashSet<>(Arrays.asList(annotation.roles()));
roles.retainAll(loggedUserProvider.getRoles());
return isNotEmpty(roles.toArray(new String[0]));
}
return false;
}
}
Config class
@Configuration
@RequiredArgsConstructor
class JacksonConfig {
private final JsonSerializerRestrictToIntrospector serializerRestrictToIntrospector;
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> {
builder.annotationIntrospector(serializerRestrictToIntrospector);
};
}
}