基于方法权限控制有三种,但都是基于aop的,所以使用需要在springmvc.xml中开启<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
一.JSR-250注解 @RolesAllowed 表示访问对应方法时所应该具有的角色
使用前需要导入Jsr-250-api依赖,开启注解 <security:global-method-security jsr250-annotations="enabled"/>
@RolesAllowed("ROLE_ADMIN") //拥有该角色的才能访问次方法 public ModelAndView findAll() { ModelAndView mv = new ModelAndView(); List<Permission> permissionList=permissionService.findAll(); mv.addObject("permissionList",permissionList); mv.setViewName("permission-list"); return mv; }
二.@Secured注解,这个是springsecurity提供的,不用导入额外依赖
使用前开启注解 <security:global-method-security secured-annotations="enabled"/>
@Secured("ROLE_ADMIN") //拥有该角色的才能访问次方法 public ModelAndView findAll(@RequestParam(name = "page",defaultValue = "1") int page, @RequestParam(name = "pageSize",defaultValue = "4") int pageSize){ ModelAndView mv= new ModelAndView(); List<Product> productList=productService.findAll(page,pageSize); PageInfo pageInfo = new PageInfo(productList); mv.addObject("pageInfo",pageInfo); mv.setViewName("product-list"); return mv; }
三.表达式的注解@PreAuthorize
使用前开启注解 <security:global-method-security pre-post-annotations="enabled"/>
注意:PreAuthorize(".....")中采用的是SpEL表达式,常用的有:hasRole('ROLE_USER'),hasAnyRole('ROLE_USER','ROLE_ADMIN',...)
authentication.principal.username=='tom' -->用户名为tom的才能访问
@PreAuthorize("hasRole('ROLE_ADMIN')")//使用SpEL表达式,有该角色才能访问次方法 public ModelAndView findAll(@RequestParam(name = "page",defaultValue = "1") int page, @RequestParam(name = "pageSize",defaultValue = "4") int pageSize){ ModelAndView mv= new ModelAndView(); List<Product> productList=productService.findAll(page,pageSize); PageInfo pageInfo = new PageInfo(productList); mv.addObject("pageInfo",pageInfo); mv.setViewName("product-list"); return mv; }
------------------------------------------------------------------------------------------------------
一. 页面端标签控制权限与用户名显示
开启aop自动代理<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
1).导入依赖spring-security-taglibs
2).页面引入<%@taglib uri="http://www.springframework.org/security/tags" prefix="security"%>
<security:authorize access="hasRole('ROLE_ADMIN')"> //拥有该角色才显示里面的内容,否者隐藏起来 <li id="system-setting"><a href="${pageContext.request.contextPath}/sysLog/findAll"> <i class="fa fa-circle-o"></i> 访问日志 </a></li> </security:authorize>
显示用户名也需要导入依赖和引入标签
<security:authentication property="principal.username"></security:authentication> <security:authentication property="name"></security:authentication> //上面两种都可以显示登录用户名