基於方法權限控制有三種,但都是基於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> //上面兩種都可以顯示登錄用戶名