I need to implement an authorization expression on multiple controllers. For this I have decided to create a personalized annotation that facilitates its use. The problem is that the authorization expression requires a parameter (an id) that can be obtained in different ways in each controller. Then
I put the annotation:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@PreAuthorize("@authorizationService.hasAdminRole() || ( @authorizationService.hasParentRole() && @authorizationService.isYourSon(#son) )")
public @interface OnlyAccessForAdminOrParentOfTheSon {
String son() default "";
}
The problem is that I do not know how to get the value of the "son" attribute of the annotation to use in the SPEL authorization expression.
The notation I use as follows:
@OnlyAccessForAdminOrParentOfTheSon(son = "#id")
@OnlyAccessForAdminOrParentOfTheSon(son = "#socialMedia.son")
Someone knows how I can fix this.
SpEL expressions can be used with XML or annotation based configuration metadata for defining BeanDefinitions. In both cases the syntax to define the expression is of the form #{ <expression string> } .
Using ExpressionParser. ExpressionParser is responsible for parsing expression strings. In this example, SpEL parser will simply evaluate the string 'Any String' as an expression.
Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL.
You can't achieve like this, but spring Security methods allowing to define some custom authorization rules easily. These rules can grant or deny some of the operations for a particular user.
You need to create a custom service/component which will athenticate the request as per your requirement using @PreAuthorize annotationa with expression.
public interface CustomAuthorization {
boolean onlyAccessForAdminOrParentOfTheSon(final UserDetails principal, final long id) ;
}
Implementation :
@Component("customAuthorization")
public final class CustomAuthorizationImpl implementes CustomAuthorization {
@Override
public boolean onlyAccessForAdminOrParentOfTheSon(final UserDetails principal, final long id) {
return // add you authentication condition;
}
}
now you can use it with @PreAuthorize annotationa with expression
@Service
public final class HelloService {
@PreAuthorize("@customAuthorization.onlyAccessForAdminOrParentOfTheSon(principal, #id)")
public String testMe(String id) {
return "test successfully";
}
}
you can use it with and service/controller action, also you can modify the parameter as per your requirement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With