如何在Spring Security 6.1.0(Sping Boot 3.1.0)中设置角色层次结构

2mbi3lxu  于 2023-05-27  发布在  Spring
关注(0)|答案(1)|浏览(223)

最近,我想知道如何使角色层次结构在Spring Security 6.0.2中工作,而不像这样编写bean

@Bean
public AuthorityAuthorizationManager<RequestAuthorizationContext>
        guestAuthorityAuthorizationManager() {
    AuthorityAuthorizationManager<RequestAuthorizationContext>
            objectAuthorityAuthorizationManager =
                    AuthorityAuthorizationManager.hasAuthority(GUEST.getRole());
    objectAuthorityAuthorizationManager.setRoleHierarchy(roleHierarchy());
    return objectAuthorityAuthorizationManager;
}

对于常见的平面角色层次结构,如ADMIN > USER > STAFF > GUEST

42fyovps

42fyovps1#

升级到Spring 6.1.0(附带Sping Boot 3.1.0依赖项训练)后,解决方案只是引入RoleHierarchy bean,如

@Bean
public RoleHierarchy roleHierarchy() {
    RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
    hierarchy.setHierarchy("ROLE_ADMIN > ROLE_STAFF > ROLE_USER > ROLE_GUEST");
    return hierarchy;
}

Spring会自动使用它。
示例:

http.authorizeHttpRequests(authorizeHttpRequests ->
   authorizeHttpRequests
      .requestMatchers(
         new AntPathRequestMatcher(ACTUATOR_URL_PATTERN),
         new AntPathRequestMatcher(LOGIN_2FA_FIRST_STEP_URL_PATTERN),
         new AntPathRequestMatcher(LOGIN_2FA_SECOND_STEP_URL_PATTERN),
         new AntPathRequestMatcher(LOGIN_FORM_URL_PATTERN),
         new AntPathRequestMatcher(OAUTH_URL_PATTERN),
         new AntPathRequestMatcher(PASSWORD_URL_PATTERN)
      )
      .permitAll()
      .requestMatchers(
         new AntPathRequestMatcher(LOGOUT_URL_PATTERN)
      )
      .hasRole("GUEST")
      .requestMatchers(
         new AntPathRequestMatcher(ADMIN_URL_PATTERN),
         new AntPathRequestMatcher(API_URL_PATTERN),
         new AntPathRequestMatcher(MAILING_URL_PATTERN)
      )
      .hasRole("ADMIN")
      .anyRequest()
      .authenticated());

注意到

  • .hasRole()没有“ROLE_”前缀
  • 此外,现在您需要在http.authorizeHttpRequests(...)的括号内使用configurer(我在这里使用lambda)。RoleHierarchy在这里使用。

好好享受吧!

相关问题