权限控制
导入依赖
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
配置文件 (加在springmvc的配置文件中,因为这些注解都是在controler层里面生效的)
<security:global-method-security jsr250-annotations="enabled"/>
.JSR-250注解
@RolesAllowed表示访问对应方法时所应该具有的角色
示例: @RolesAllowed({“USER”, “ADMIN”}) 该方法只要具有"USER",
"ADMIN"任意一种权限就可以访问。这里可以省 略前缀ROLE_,实际
的权限可能是ROLE_ADMIN
@PermitAll表示允许所有的角色进行访问,也就是说不进行权限控制 @DenyAll是和PermitAll相反的,表示无论什么角色都不能访问
.@Secured注解
<security:global-method-security secured-annotations="enabled"/>
@Secured注解标注的方法进行权限控制的支持,其值默认为disabled
示例:
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account readAccount(Long id);
@Secured("ROLE_TELLER")
支持表达式的注解
<security:global-method-security pre-post-annotations="disabled"/>
@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')");
@PostFilter 允许方法调用,但必须按照表达式来过滤方法的结果
@PreFilter 允许方法调用,但必须在进入方法之前过滤输入值
异常处理
有三种处理方式
- 在spring-securi