在 SpringBoot 应用程序中使用 @RolesAllowed 的异常

Nuñ*_*ada 5 java spring spring-security thymeleaf spring-boot

我有一个基本的 SpringBoot 应用程序。使用 Spring Initializer、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为可执行 JAR 文件。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
}
Run Code Online (Sandbox Code Playgroud)

companyService 被注入并且不为空。删除@RolesAllowed工作正常

@Autowired
CompanyService companyService;
Run Code Online (Sandbox Code Playgroud)

在我的 applicationConfig 中:

@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled=true, securedEnabled=true, prePostEnabled=true)
Run Code Online (Sandbox Code Playgroud)

我有一个这样注释的控制器方法

@ModelAttribute("companies")
    @RolesAllowed({"ROLE_ADMIN"})
    public Iterable<Company> companies(){
        return companyService.findAll();
    }
Run Code Online (Sandbox Code Playgroud)

当我尝试访问控制器时,我遇到了一个没有信息的应用程序异常:

<div th:utext="'Failed URL: ' +  ${url}"    th:remove="tag">${url}</div>
<div th:utext="'Exception: ' + ${message}"  th:remove="tag">${message}</div>
<div th:utext="'Exception: ' + ${trace}"    th:remove="tag">${trace}</div>


<!--
    Failed URL: null
    Exception: No message available
    Exception: null

    -->
Run Code Online (Sandbox Code Playgroud)

在到达控制器之前,我检查用户的角色

System.out.println("Authorities -> " +
    SecurityContextHolder.getContext().getAuthentication().getAuthorities())
Run Code Online (Sandbox Code Playgroud)

这是结果:

Authorities -> [Authority [authority=ROLE_BASIC], Authority [authority=ROLE_ADMIN]]
Run Code Online (Sandbox Code Playgroud)

使用相同的结果:

  @ModelAttribute("companies")
    @Secured("ADMIN")
    public Iterable<Company> companies(){
        return companyService.findAll();
    }
Run Code Online (Sandbox Code Playgroud)

或者 @Secured("ROLE_ADMIN")

在调试中:

 42410 [http-nio-8080-exec-7] DEBUG o.s.s.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@65eab2b2, returned: 1
42410 [http-nio-8080-exec-7] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Authorization successful
42410 [http-nio-8080-exec-7] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - RunAsManager did not change Authentication object
42410 [http-nio-8080-exec-7] DEBUG o.s.security.web.FilterChainProxy - /company/list reached end of additional filter chain; proceeding with original chain
42411 [http-nio-8080-exec-7] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally
42411 [http-nio-8080-exec-7] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
42411 [http-nio-8080-exec-7] DEBUG o.a.c.c.C.[Tomcat].[localhost] - Processing ErrorPage[errorCode=0, location=/error
Run Code Online (Sandbox Code Playgroud)
  • 删除@Secured时调用公司(),并调试AffirmativeBased我得到:

    开关(结果){ case AccessDecisionVoter.ACCESS_GRANTED:返回;logger.debug("授权成功");

yt6*_*t61 4

不要使用其中任何一个@Secured,或者@RolesAllowed不再建议使用此注释。而是使用@PreAuthorize("hasAuthority('ROLE_ADMIN')")