【问题标题】:Spring Security RolesAllowed and thymeleaf sec:authorizeSpring Security RolesAllowed 和 thymeleaf sec:authorize
【发布时间】:2021-02-23 23:43:14
【问题描述】:

我有一个控制器和百里香模板。两者都包含对 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();
    }
}

【问题讨论】:

    标签: spring spring-security thymeleaf


    【解决方案1】:

    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>
    

    【讨论】:

      猜你喜欢
      • 2015-04-20
      • 2020-08-05
      • 2013-12-30
      • 2018-01-22
      • 2015-11-26
      • 2019-04-14
      • 2021-06-20
      • 2016-03-18
      • 2014-05-26
      相关资源
      最近更新 更多