我有一个基本的 SpringBoot 应用程序。使用 Spring Initializer、嵌入式 Tomcat、Thymeleaf 模板引擎,并将其打包为可执行的 JAR 文件。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
}
companyService 被注入(inject)并且不为空。删除
@RolesAllowed
工作正常@Autowired
CompanyService companyService;
在我的应用程序配置中:
@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled=true, securedEnabled=true, prePostEnabled=true)
我有一个这样注释的 Controller 方法
@ModelAttribute("companies")
@RolesAllowed({"ROLE_ADMIN"})
public Iterable<Company> companies(){
return companyService.findAll();
}
当我尝试访问 Controller 时,我遇到了一个没有任何信息的应用程序异常:
<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
-->
在到达 Controller 之前,我检查了用户的角色
System.out.println("Authorities -> " +
SecurityContextHolder.getContext().getAuthentication().getAuthorities())
这是结果:
Authorities -> [Authority [authority=ROLE_BASIC], Authority [authority=ROLE_ADMIN]]
使用相同的结果:
@ModelAttribute("companies")
@Secured("ADMIN")
public Iterable<Company> companies(){
return companyService.findAll();
}
或
@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
AffirmativeBased
时调用company()我有 :开关(结果){
案例 AccessDecisionVoter.ACCESS_GRANTED:
返回;
logger.debug("授权成功");
最佳答案
不要使用@Secured
或 @RolesAllowed
不再推荐使用此注释。而是使用 @PreAuthorize("hasAuthority('ROLE_ADMIN')")
关于java - 在 SpringBoot 应用程序中使用 @RolesAllowed 的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44085969/