【发布时间】:2015-09-20 02:47:00
【问题描述】:
我正在尝试使用 @Secured("ADMIN") 设置方法安全注释(没有任何 XML,只有 java 配置,Spring Boot)。但是通过角色访问不起作用。
安全配置:
@Configuration
@EnableWebSecurity
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter{
.....
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").fullyAuthenticated().and()
.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
.....
}
我想限制对控制器方法的访问:
@RestController
@RequestMapping("/api/groups")
public class GroupController {
@Autowired
private GroupService groupService;
@Secured("ADMIN")
@RequestMapping
public List<Group> list() {
return groupService.findAll();
}
}
通过 url 限制访问有效,使用:
.antMatchers("/api/**").hasAuthority("ADMIN")
也许我忘了指定我要按角色进行限制?
统一更新:
按照规则,@PreAuthorize("hasRole('ADMIN')")必须在Controller层还是Service层的哪一层?
【问题讨论】:
-
什么不起作用?浏览器是否没有尝试对您进行身份验证?它会忽略您提供的凭据吗?顺便说一句:您还应该发布将用户映射到管理员组的位置,也许这是有问题的区域。
-
身份验证工作正常,但任何角色的任何用户都可以访问“/api/groups”
-
你在哪里设置 ROLE 'ADMIN',你能告诉我吗??
-
尽管角色定义正确:
org.springframework.security.authentication.UsernamePasswordAuthenticationToken: Principal: SecurityUser; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ADMIN -
在这里您可以看到权限实际上是
ADMIN而不是ROLE_ADMIN。因为 RoleVoter 检查以ROLE_开头的权限,所以找不到您的权限(即ADMIN),因此弃权
标签: java spring security spring-security spring-boot