问题
So I created a class with two simple public strings
public final class Right {
private Right() {
super();
}
public static final String AUTH = "hasAuthority('admin') or hasAuthority('mod')";
}
When I used it together with the @PreAuthorize annotation at my controllers it works like a charm. I do not like that it is hardcoded. For this reason I've put the roles in the properties and I tried to use it as a component:
@Component("authRule")
public class AuthRule {
@Value("${role.administrator}")
private String roleAdmin;
@Value("${role.moderator}")
private String roleMod;
public String getRightAccess() {
return "hasAuthority('" + roleAdmin+ "')" + " or hasAuthority('" + roleMod+ "')";
}
}
When i use it in my PreAuthorize as :
@PreAuthorize("@authRule.getRightAccess()")
I am getting back an exception of Failed to convert from type [java.lang.String] to type [java.lang.Boolean] for value 'hasAuthority('admin') or hasAuthority('mod')
if I hardcoded in the PreAuthorize. I am quite confused with this. Anyone any ideas?
Thanks in advance for all the responses.
回答1:
I've had a quick read of the documentation; https://docs.spring.io/spring-security/site/docs/current/reference/html5/#el-pre-post-annotations
It's likely that the value provided to the annotation is parsed only once. I think you need it to parse twice; once to trigger your custom component's method getRightAccess(). And a second time to parse the String result returned by that method. There are examples here if you do a general search for "Boolean"; https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/html/expressions.html
// evaluates to true
boolean isMember = parser.parseExpression("isMember('Mihajlo Pupin')").getValue(
societyContext, Boolean.class);
So you probably need something like this in your getRightAccess() method;
return parser.parseExpression("hasAuthority('"+roleAdmin+"') or hasAuthority('"+roleMod+"')").getValue(Boolean.class);
来源:https://stackoverflow.com/questions/63673289/spring-preauthorize-hasauthority-exception-failed-to-convert-from-type-java-la