Spring Security的使用(二)——服务器端方法级权限控制
在服务器端我们可以通过Spring security提供的注解对方法来进行权限控制。Spring Security在方法的权限控制上
支持三种类型的注解,JSR-250注解、@Secured注解和支持表达式的注解,这三种注解默认都是没有启用的,需要
单独通过global-method-security元素的对应属性进行启用
开启注解使用
- 配置文件
<security:global-method-security jsr250-annotations=“enabled”/>
<security:global-method-security secured-annotations=“enabled”/>
<security:global-method-security pre-post-annotations=“disabled”/> - 注解开启
@EnableGlobalMethodSecurity :Spring Security默认是禁用注解的,要想开启注解,需要在继承
WebSecurityConfigurerAdapter的类上加@EnableGlobalMethodSecurity注解,并在该类中将
AuthenticationManager定义为Bean。
JSR-250注解
- @RolesAllowed表示访问对应方法时所应该具有的角色
示例:
@RolesAllowed({“USER”, “ADMIN”}) 该方法只要具有"USER", "ADMIN"任意一种权限就可以访问。这里可以省
略前缀ROLE_,实际的权限可能是ROLE_ADMIN
- @PermitAll表示允许所有的角色进行访问,也就是说不进行权限控制
- @DenyAll是和PermitAll相反的,表示无论什么角色都不能访问
支持表达式的注解
- @PreAuthorize 在方法调用之前,基于表达式的计算结果来限制对方法的访问
示例:
@PreAuthorize("#userId == authentication.principal.userId or hasAuthority(‘ADMIN’)")
void changePassword(@P(“userId”) long userId ){ }
这里表示在changePassword方法执行之前,判断方法参数userId的值是否等于principal中保存的当前用户的
userId,或者当前用户是否具有ROLE_ADMIN权限,两种符合其一,就可以访问该方法。
- @PostAuthorize 允许方法调用,但是如果表达式计算结果为false,将抛出一个安全性异常
示例:
@PostAuthorize
User getUser(“returnObject.userId == authentication.principal.userId or
hasPermission(returnObject, ‘ADMIN’)”);
@Secured注解
@Secured注解标注的方法进行权限控制的支持,其值默认为disabled。
示例:
@Secured(“IS_AUTHENTICATED_ANONYMOUSLY”)
public Account readAccount(Long id);
@Secured(“ROLE_TELLER”)