拒绝具有所需角色的java用户
我有以下配置文件:
//AUTHORIZATION
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable();
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/home", "/").permitAll()
.antMatchers("/api/example1/**").hasAnyRole(ADMIN_ACCESS, EXAMPLE1_USER, EXAMPLE1_ADMIN)
.antMatchers("/api/example2/**").hasAnyRole(ADMIN_ACCESS, EXAMPLE2_USER, EXAMPLE2_ADMIN)
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.usernameParameter("username")
.passwordParameter("pass")
.defaultSuccessUrl("/home")
.and()
.logout()
.invalidateHttpSession(true)
.clearAuthentication(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login")
.permitAll()
.and()
.rememberMe()
.tokenValiditySeconds(600)
.key("secretKey")
.rememberMeParameter("checkRememberMe");
}
我使用该用户登录,请注意它有ROLE_ADMIN
(基本上,访问所有内容):
{
"username": "test",
"pass": "test",
"roles": "ROLE_ADMIN",
"permissions": "",
"company": "test"
}
通过Thymeleaf表单正确登录。但是,每当我尝试访问锁定在角色后面的端点时,都会出现错误500
我在控制器中尝试了不同的注释,如您所见:
@RestController
@RequestMapping("/api/example1")
@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_EXAMPLE1_USER', 'ROLE_EXAMPLE1_ADMIN')")
public class MyController {
@Autowired
private MyService service;
@GetMapping("/getAll")
public List<MyEntity> get() {
return service.get();
}
@GetMapping("/getAllAuth")
@PreAuthorize("hasAuthority('ROLE_EXAMPLE1_ADMIN') or hasAuthority('ROLE_ADMIN')")
public List<MyEntity> getAuth() {
return service.get();
}
@GetMapping("/getAllAuth2")
@PreAuthorize("hasAnyRole('ROLE_EXAMPLE1_ADMIN', 'ROLE_ADMIN')")
public List<MyEntity> getAuth2() {
return service.get();
}
}
然而,我在所有这些方面都被否定了。我尝试使用角色和权限
为澄清起见,EXAMPLE1_USER == ROLE_EXAMPLE1_USER
,其他人也一样。我确保这不是打字错误
你知道问题是什么吗
# 1 楼答案
我通过将注释和安全文件中的
hasAnyRole
更改为hasAnyAuthority
使其工作