Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security @PreAuthorize hasRole() properties injection

Assuming that my Spring Security and properties are configured properly, I would like to use role name from property like

@PreAuthorize("hasRole('${role.rolename}')")
public void method() {}

I have tried like in above code sample but it does not work (it takes '${role.rolename}' String as role to compare)

If I switch to

@PreAuthorize("hasRole('ROLE_ADMIN')")
public void method() {}

it works just fine. My motivation to such usage is better flexibility in application tests on various environments.

like image 830
Paweł Kaczorowski Avatar asked Aug 13 '13 10:08

Paweł Kaczorowski


2 Answers

Try to remove '' signs:

@PreAuthorize("hasRole(${role.rolename})")
public void method() {}

EDIT. I am sure that there is a better way, but as a workaround you can call some method on some bean:

@Component("appVariablesHolder")
public class AppVariablesHolder {

    @Value("${role.rolename}") 
    private String someRole;

    public String getSomeRole() {
        return this.someRole;
    }
}

@PreAuthorize("hasRole(@appVariablesHolder.getSomeRole())")
public void method() {}
like image 71
Maksym Demidas Avatar answered Oct 13 '22 13:10

Maksym Demidas


I've found that you can just grab the propertyResolver and pull values directly from that, instead of writing your own class as was suggested by @Maksym.

Exammple:

@PreAuthorize("hasRole(@environment.getProperty('role.rolename')")
public void method() {}
like image 23
Ben L. Avatar answered Oct 13 '22 12:10

Ben L.