SpringSecurity的權限控制


菜單控制:

 

 可以用來判斷這個用戶是不是有這些角色,沒有的話就不展示

 

數據控制:

由於數據都是從后端查的,在后端控制權限就可以了

    <!--
        開啟權限控制注解支持
        jsr250-annotations="enabled"表示支持jsr250-api的注解,需要jsr250-api的jar包
        pre-post-annotations="enabled"表示支持spring表達式注解
        secured-annotations="enabled"這才是SpringSecurity提供的注解
     -->
    <security:global-method-security jsr250-annotations="enabled"
                                     pre-post-annotations="enabled"
                                     secured-annotations="enabled"/>

注:這個要放在mvc的容器中,因為子容器可以訪問到主容器,主容器訪問不到子容器

/表示當前類中所有方法都需要ROLE_ADMIN或者ROLE_PRODUCT才能訪問
@Controller
@RequestMapping("/product")
@RolesAllowed({"ROLE_ADMIN","ROLE_PRODUCT"})//JSR-250注解
public class ProductController {
@RequestMapping("/findAll")
public String findAll(){
return "product-list";
}
}
//表示當前類中findAll方法需要ROLE_ADMIN或者ROLE_PRODUCT才能訪問
@Controller
@RequestMapping("/product")
public class ProductController {
@RequestMapping("/findAll")
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_PRODUCT')")//spring表達式注解
public String findAll(){
return "product-list";
}
}
//表示當前類中所有方法都需要ROLE_ADMIN或者ROLE_PRODUCT才能訪問
@Controller
@RequestMapping("/product")
@Secured({"ROLE_ADMIN","ROLE_PRODUCT"})//SpringSecurity注解
public class ProductController {
@RequestMapping("/findAll")
public String findAll(){
return "product-list";
}
}

但是會報403無法訪問

方式一:在 spring-security.xml配置文件中處理

<!--設置可以用spring的el表達式配置Spring Security並自動生成對應配置組件(過濾器)-->
<security:http auto-config="true" use-expressions="true">
<!--省略其它配置-->
<!--403異常處理-->
<security:access-denied-handler error-page="/403.jsp"/>
</security:http>

方式二:在 web.xml中處理

<error-page>
    <error-code>403</error-code>
    <location>/403.jsp</location>
</error-page>

方式三:編寫異常處理器

/**
 * @author WGR
 * @create 2020/3/2 -- 17:33
 */
@ControllerAdvice
public class ControllerExceptionAdvice {

    //只有出現AccessDeniedException異常才調轉403.jsp頁面
    @ExceptionHandler(AccessDeniedException.class)
    public String exceptionAdvice(){
        System.out.println("1234");
        return "forward:/403.jsp";
    }
}

 

注:如果是spring項目,也要把這個掃描進去。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM