在服务器端我们可以通过Spring security提供的注解对方法来进行权限控制。Spring Security在方法的权限控制上支持三种类型的注解:JSR-250注解
、@Secured注解
和支持表达式的注解
。
这三种注解默认都是没有启用的,需要单独通过global-method-security元素的对应属性进行启用
JSR-250注解的使用步骤
(1) 在spring-security.xml中添加: <security:global-method-security jsr250-annotations="enabled"></security:global-method-security>
(2) 在Controller中的指定方法上使用
@RoleAllowed注解是一个String类型的数组,里面可以写角色的名称。代表:当前方法只有ADMIN才能访问。此时findAll方法只有ADMIN角色才能用
(3)导入jar包: jsr250-api-1.0.jar
@Secured注解的使用步骤
1、在spring-security.xml中添加:<security:global-method-security secured-annotations="enabled"></security:global-method-security>
2、在Controller中的指定方法上使用
注意:在使用 JSR250注解时,可以省略ROLE前缀。而我们现在使用的@Secured是不能省略前缀的。
支持表达式的注解
-
@PreAuthorize 在方法调用之前,基于表达式的计算结果来限制对方法的访问
示例:
(1)<security:global-method-security pre-post-annotations="enabled"></security:global-method-security>
(2)在Controller中的指定方法上使用
@PreAuthorize("authentication.principal.username == 'tom'")
//当前用户name为tom
@PreAuthorize("hasRole('ROLE_ADMIN')")
//这里用到了SPEL表达式 -
@PostAuthorize 允许方法调用,但是如果表达式计算结果为false,将抛出一个安全性异常
示例:
@PostAuthorize
User getUser(“returnObject.userId == authentication.principal.userId or
hasPermission(returnObject, ‘ADMIN’)”); -
@PostFilter 允许方法调用,但必须按照表达式来过滤方法的结果
-
@PreFilter 允许方法调用,但必须在进入方法之前过滤输入值
页面端权限控制
1、导入jar包:spring-security-taglibs-5.0.1.RELEASE.jar
2、在页面导入<%@taglib uri="http://www.springframework.org/security/tags" prefix="security"%>
3、在页面上使用
(1)authentication 可以获取当前正在操作的用户信息
示例:
<div class="pull-left info">
<p>
<security:authentication property="principal.username"></security:authentication>
</p>
<a href="#"><i class="fa fa-circle text-success"></i> 在线</a>
</div>
这样就能显示 ***在线
(2)authorize 可以控制页面上某些标签是否可以显示
<li id="system-setting">
<security:authorize access="hasRole('ADMIN')">
<a
href="${pageContext.request.contextPath}/user/findAll.do"> <i
class="fa fa-circle-o"></i> 用户管理
</a>
</security:authorize>
</li>
如果当前的用户是ADMIN,就可以看到“用户管理”