我有一个控制器和thymelaf模板。两者都包含对Spring Security角色的限制。我不喜欢我把这些角色写在两个地方。我可以在一次复仇中写一系列角色并使用它吗?我试着通过枚举像
@RolesAllowed(ALLOWED_ROLES)
和
public static final String[] ALLOWED_ROLES = {Role.ADMIN.toString(), Role.EDITOR.toString()};
,但编译器需要一个常量(使用枚举类型作为@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();
}
}
在Spring注释中使用静态变量
使用@PreAuthorize 的多个角色
如何为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>