我有一个基本的SpringBoot应用程序。使用Spring Initializer,嵌入式Tomcat,Thymeleaf模板引擎和包作为可执行的JAR文件。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
}
注入companyService而不是null。删除@RolesAllowed
可以正常使用
@Autowired
CompanyService companyService;
在我的applicationConfig中:
@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled=true, securedEnabled=true, prePostEnabled=true)
我有一个像这样的
控制器的方法@ModelAttribute("companies")
@RolesAllowed({"ROLE_ADMIN"})
public Iterable<Company> companies(){
return companyService.findAll();
}
当我尝试访问控制器时,我有一个没有信息的应用程序异常:
<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
-->
在到达控制器之前,我会检查用户的角色
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
时,会调用companies():
switch(result){ 案例AccessDecisionVoter.ACCESS_GRANTED: 返回; logger.debug(&#34;授权成功&#34;);
答案 0 :(得分:0)
companies()
注释后,会调用@Secured
吗?
如果是,那么尝试调试
org.springframework.security.access.vote.AffirmativeBased
最有可能的是,首先会在检查您的网址时调用它,然后当您调用由companies()
注释保护的@Secured
方法时会调用它,并且由于某种原因,第二次检查失败。
另见: https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#authz-pre-invocation
答案 1 :(得分:0)
不要使用@Secured
或@RolesAllowed
不再使用此注释。而是使用@PreAuthorize("hasAuthority('ROLE_ADMIN')")