1. 程式人生 > 程式設計 >SpringSecurity許可權控制實現原理解析

SpringSecurity許可權控制實現原理解析

選單控制:

SpringSecurity許可權控制實現原理解析

SpringSecurity許可權控制實現原理解析

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

SpringSecurity許可權控制實現原理解析

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專案,也要把這個掃描進去。

SpringSecurity許可權控制實現原理解析

SpringSecurity許可權控制實現原理解析

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。