如何解决Spring @PreAuthorize hasAuthority异常无法将值'hasAuthority
所以我用两个简单的公共字符串创建了一个类
public final class Right {
private Right() {
super();
}
public static final String AUTH = "hasAuthority('admin') or hasAuthority('mod')";
}
当我在控制器上将它与@PreAuthorize批注一起使用时,它就像一个魅力。我不喜欢它是硬编码的。因此,我将角色放入属性中,并尝试将其用作组件:
@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+ "')";
}
}
当我在PreAuthorize中使用它时:
@PreAuthorize("@authRule.getRightAccess()")
我返回了一个异常,无法将值'hasAuthority('admin')或hasAuthority('mod')从类型[java.lang.String]转换为类型[java.lang.Boolean]
如果我在PreAuthorize中进行了硬编码。我对此很困惑。任何想法吗?
预先感谢所有回复。
解决方法
我已经快速阅读了文档; https://docs.spring.io/spring-security/site/docs/current/reference/html5/#el-pre-post-annotations
提供给注释的值可能仅被解析一次。我认为您需要解析两次;一次触发您的自定义组件的方法getRightAccess()。第二次解析该方法返回的String结果。如果您对“布尔”进行常规搜索,则这里有一些示例。 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);
因此您可能在getRightAccess()方法中需要这样的东西;
return parser.parseExpression("hasAuthority('"+roleAdmin+"') or hasAuthority('"+roleMod+"')").getValue(Boolean.class);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。