Search code examples
javajakarta-eeejbjax-rsbean-validation

Validation rule that depends on currently logged principal


I have some business method in an EJB that recieves a DTO as argument, ie:

public void someMethod(SomeClass someArgument);

I would like to define a custom validator that validates the argument (notice that i would like to validate it as a parameter, not at class level, although if someone have a workaround that involves that it's welcome). The validation needs data from the currently logged principal, for example, by injecting it with @Context annotation the SecurityContext.

So, my first approach was to implement a new ConstraintValidator, with PARAMETER target, for SomeClass. The thing is, i think that injecting the SecurityContext with @Context inside this ConstraintValidator wouldn't work, as the bean-validation api mandates that the isValid method should be thread-safe, so i guess this validation instance is reused concurrently, and then the injected SecurityContext wouldn't work.

Is my suspicion right? How would you handle this use-cases, in which you need to use security context provided information to perform validation? I know how to do it with spring security, but not in javaee (version 7) environment.


Solution

  • Bean validation v1.1 is integrated with cdi. In theory you can inject the predefined bean Principal in your validator. There is no threading issue as the constraint is called by the BV framework. So in your custom validator I would do:

    @Inject private Principal principal