Spring Security 提供了一些访问控制的注解,这些注解需要开启 @EnableGlobalMethodSecurity
后方可生效。
这些注解通常被写到 Service 接口或方法上、或者 Controller 和方法上,一般来说,写在控制器上比较常见,可以控制接口 URL 是否允许被访问。
@Secured
需要在 Application 启动类配置 securedEnabled
@EnableGlobalMethodSecurity(securedEnabled = true)
方可生效。
使用形式:
@Secured("ROLE_ADMIN")
@RequestMapping("/demo")
@ResponseBody
public String demo() {
return "demo";
}
通过配置 value 值,确定能够访问的权限。
注意,如果你配置了 WebSecurityConfig,需要在其中放行 /demo :
http.authorizeRequests() .antMatchers("/showLogin", "/showFail").permitAll() .antMatchers("/demo").permitAll() .anyRequest().authenticated();
此时,你会发现,配置 Secured 之后,/demo 仍然会被保护,只有认证后角色是 ADMIN 的用户才可访问。
@PreAuthorize / @PostAuthorize
需要在 Application 启动类配置 prePostEnabled
@EnableGlobalMethodSecurity(prePostEnabled = true)
方可生效。
- @PreAuthorize 表示访问方法或类在执行之前先判断权限,使用较多,注解的参数和 access() 方法参数取值相同,都是权限表达式,并支持自定义。
- @PostAuthorize 表示方法或类执行结束后判断权限,使用很少。
使用形式:
@PreAuthorize("hasAuthority('admin1')")
@RequestMapping("/demo")
@ResponseBody
public String demo() {
return "demo";
}
外层用双引号,内层用单引号(或者反斜线转义)。
小结
- 在开启
@EnableGlobalMethodSecurity(securedEnabled = true)
后,@Secured
注解可以生效,它的作用是,保护函数或类,用户必须满足 value 指定的权限(或角色)才可以访问; - 在开启
@EnableGlobalMethodSecurity(prePostEnabled = true)
后,@PreAuthorize / @PostAuthorize
注解可以生效,它们的作用是,保护函数或类,在执行前/后进行权限判断,用户是否满足 value 指定的认证权限表达式,权限表达式的内容就是 access 函数的参数的内容。