Search code examples
springspring-security

Spring Security and super class


fIn my app I'm using the Spring Security and have defined next classes.

public abstract class AbstractService {

    public void save(){
.....
    }
}

@Service
@PreAuthorize(SpelAuthorityExpressions.SOME_KIND_OF_ACCESS)
publist class UserService  extends AbstractService {

}

@Service
@PreAuthorize(SpelAuthorityExpressions.SOME_KIND_OF_ACCESS_X)
publist class XService extends AbstractService{

}

I need @PreAuthorize annotation from the child class to be applied to the super class methods( for example: save()).Is there any way to achieve it by avoiding to override super class methods? AbstractService will have more than one child( > 10) wherein each have own @PreAuthorize value.


Solution

  • You can try to use SPEL for that.

    Because AFAIK, you must annotate methods or the superclass or the superclass itself, and the annotation must be a plain string (or a static final which is the same). But the string may contain SPEL expressions that will reference the target object. Example if only roles were used :

    @PreAuthorize("hasAnyRole(#root.this.requiredRoles)")
    public abstract class AbstractService {
        public abstract String getRequiredRoles();
        public void save(){
    .....
        }
    }
    @Service
    @PreAuthorize(SpelAuthorityExpressions.SOME_KIND_OF_ACCESS)
    publix class UserService  extends AbstractService {
        @Override
        public String getRequiredRoles() {
            return "ROLE_USER, ROLE_CLIENT";
        }
        ....
    }
    

    As the condition is evaluated by SPEL at runtime, it will use the overriden getter and the list of roles can be defined in child class.

    Without knowing what are your requirements for authorization expressions, I cannot be sure if that will do the trick, but I successfully use that for caching methods in a superclass, with keys depending on values in child classes.