我有一个控制器和百里香模板。两者都包含对Spring Security角色的限制。我不喜欢在两个地方写这些角色。我可以在一次复仇中编写一系列角色并使用它吗?我试图通过像这样的枚举来做
@RolesAllowed(ALLOWED_ROLES)
和
public static final String[] ALLOWED_ROLES = {Role.ADMIN.toString(), Role.EDITOR.toString()};
,但是编译器需要一个常量(Use Enum type as a value parameter for @RolesAllowed-Annotation)。有一些不错的解决方案可以在一处描述允许的角色吗?
控制器:
@Controller
@RolesAllowed({"ROLE_ADMIN", "ROLE_EDITOR"})
public class MenuEditorController {
...
}
胸腺:
<ul th:fragment = "nav-default">
<li><a th:href="@{/}">Home</a></li>
<li sec:authorize="hasAnyRole('ROLE_ADMIN', 'ROLE_EDITOR')"><a th:href="@{/admin/menu}">menu editor</a></li>
</ul>
角色枚举:
public enum Role implements GrantedAuthority {
ADMIN,
EDITOR,
CONSULTANT,
CLIENT;
@Override
public String getAuthority() {
return "ROLE_" + name();
}
}
答案 0 :(得分:0)
Using static variables in Spring annotations
Multiple roles using @PreAuthorize
How to use constant for Spring Security hasRole
@Controller
//@PreAuthorize("hasAnyRole(T(ru.knastnt.prj.web.admin.MenuEditorController).ALLOWED_ROLES)")
@PreAuthorize("hasAnyRole(@menuEditorController.ALLOWED_ROLES)")
public class MenuEditorController {
public static final String[] ALLOWED_ROLES = {Role.ADMIN.toString(), Role.EDITOR.toString()};
...
<ul th:fragment = "nav-default">
<li sec:authorize="hasAnyRole(@menuEditorController.ALLOWED_ROLES)"><a th:href="@{/admin/menu}">menu editor</a></li>
</ul>