0

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);
    };
  }
}
Denis Kisina
  • 350
  • 4
  • 19
  • Probably `JsonView` annotation can help you to hide or show fields inside pojo, can you submit a minimal example of logged or not users and their pojos? – dariosicily Jan 29 '23 at 17:20
  • You should not use `hasIgnoreMarker` here because it does not depend from an instance of the class but from the class itself. It is "checked" only once since annotations should not change during the app life-cycle. In this case you can use custom serialiser. – Michał Ziober Jan 29 '23 at 23:33
  • @MichałZiober Thank you for clarification. I now understand why it was behaving as it is. I will try to implement a custom serializer and tell you. Thanks again. – Denis Kisina Jan 30 '23 at 01:45
  • @dariosicily I can come up with one later. – Denis Kisina Jan 30 '23 at 01:47
  • @DenisKisina, take a look at [How to inject dependency into Jackson Custom deserializer](https://stackoverflow.com/questions/54777586/how-to-inject-dependency-into-jackson-custom-deserializer/54795765#54795765) – Michał Ziober Jan 30 '23 at 15:43

0 Answers0