如何在 TienChin 項目中自定義權限表達式

在 SpEL 表達式中,如果上來就直接寫要執(zhí)行的方法名,那么就說明這個方法是 RootObject 對象中的方法,如果要執(zhí)行其他對象的方法,那么還需要寫上對象的名字,例如如下兩個例子:

<pre class="prettyprint hljs kotlin" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">`@PreAuthorize("hasAuthority('system:user:add')")
public String add() {
    return "add";
}` </pre>

上面這個例子中,表達式中的方法是 hasAuthority,沒有寫對象名,那么就說明這個方法是 SpEL 中 RootObject 對象中的方法。

<pre class="prettyprint hljs kotlin" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">`@PreAuthorize("@ss.hasPermi('monitor:operlog:list')")
@GetMapping("/list")
public TableDataInfo list(SysOperLog operLog) {
    startPage();
    List<SysOperLog> list = operLogService.selectOperLogList(operLog);
    return getDataTable(list);
}` </pre>

上面這個例子中,權限注解中的表達式方法是 @ss.hasPermi('monitor:operlog:list') ,其中 ss 是指 Spring 容器中的一個對象名,hasPermi 則是這個對象中的方法。

好啦,經過前面文章的學習,這些基本知識大家都已經掌握了。

2. 如何自定義

其實上面給出來的第二個例子就是一個自定義的例子。

不過,這種自定義方式太自由了,自由到沒有在 Spring Security 架構內完成這件事。所以,今天我想和小伙伴們聊一聊,如何在不使用第三方對象的情況下,來自定義一個權限判斷的表達式。

首先小伙伴們知道,我們在 @PreAuthorize 注解中使用的不用加對象名就能調用的權限方法,如 hasAuthority 、 hasPermission 、 hasRole 、 hasAnyRole 等,基本上都是由 SecurityExpressionRoot 及其子類提供的,準確來說是由 MethodSecurityExpressionRoot 類提供的。

MethodSecurityExpressionRoot 類實際上繼承自 SecurityExpressionRoot,只不過增加了過濾對象以及返回值對象。我們來看下 MethodSecurityExpressionRoot 的方法摘要:

再來看看 SecurityExpressionRoot 中的方法:

這些就是 RootObject 對象中的所有方法了,也是我們能夠在 @PreAuthorize 注解中使用的所有方法了。

那么現(xiàn)在想在已有方法上繼續(xù)擴展新方法,那么我們可以通過自定義類繼承自 SecurityExpressionRoot 對象,擴展這個 RootObject 對象,在該對象中繼續(xù)添加新的方法,進而實現(xiàn)自定義權限表達式。

好啦,說干就干,開搞!

本文的案例在前文的基礎上繼續(xù)完成,所以這里我就不從頭開始寫了。

3. 自定義 ExpressionRoot

首先我們自定義一個類繼承自 SecurityExpressionRoot 并實現(xiàn) MethodSecurityExpressionOperations 接口(本來直接繼承自 MethodSecurityExpressionRoot 即可,但是因為這個類不是 public 的,沒法繼承,所以我們就實現(xiàn) MethodSecurityExpressionOperations 接口即可):

<pre class="prettyprint hljs xml" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">`public class CustomSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

    private Object filterObject;
    private Object returnObject;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * Creates a new instance
     *
     * @param authentication the {@link Authentication} to use. Cannot be null.
     */
    public CustomSecurityExpressionRoot(Authentication authentication) {
        super(authentication);
    }

    /**
     * 判斷當前對象是否具備某一個權限
     * @param permission
     * @return
     */
    public boolean hasPermission(String permission) {
        //獲取當前登錄用戶所具有的權限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
  for (GrantedAuthority authority : authorities) {
  if (antPathMatcher.match(authority.getAuthority(), permission)) {
  return  true;
 }
 }
  return  false;
 }

  /**
 * 是否具備多個權限中的任意一個權限
 * @param permissions
 * @return
 */
  public  boolean  hasAnyPermissions(String... permissions) {
  if (permissions == null || permissions.length == 0) {
  return  false;
 }
 Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
  for (GrantedAuthority authority : authorities) {
  for (String permission : permissions) {
  if (antPathMatcher.match(authority.getAuthority(), permission)) {
  return  true;
 }
 }
 }
  return  false;
 }

  public  boolean hasAllPermissions:(String... permissions) {
 Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
  if (permissions == null || permissions.length == 0) {
  return  false;
 }
  for (String permission : permissions) {
  boolean flag = false;
  for (GrantedAuthority authority : authorities) {
  if (antPathMatcher.match(authority.getAuthority(), permission)) {
 flag = true;
 }
 }
  if (!flag) {
  return  false;
 }
 }
  return  true;
 }

  @Override
  public  void  setFilterObject(Object filterObject) {
  this.filterObject = filterObject;
 }

  @Override
  public Object getFilterObject() {
  return filterObject;
 }

  @Override
  public  void  setReturnObject(Object returnObject) {
  this.returnObject = returnObject;
 }

  @Override
  public Object getReturnObject() {
  return returnObject;
 }

  @Override
  public Object getThis() {
  return  this;
 }
}` </pre>

加了 @Override 注解的方法,都是普普通通的常規(guī)方法,沒啥好說的。我們自己主要實現(xiàn)了三個方法,分別是:

  • hasPermission:判斷當前用戶是否具備某一個給定的權限。

  • hasAnyPermissions:判斷當前用戶是否具備給定的多個權限中的某一個。

  • hasAllPermissions:判斷當前用戶是否具備所有的給定的權限。

這里邊的邏輯我就不啰嗦了,都是基本的 Java 語法而已。

另外,用 AntPathMatcher 做比對是為了支持通配符,這個在上篇文章中已經說過了,這里不再贅述。

Spring Security 中,MethodSecurityExpressionRoot 的配置是通過 DefaultMethodSecurityExpressionHandler 來完成的,現(xiàn)在我們自定義了 CustomSecurityExpressionRoot,那也得有一個 Handler 來配置 CustomSecurityExpressionRoot,所以,再來一個類繼承自 DefaultMethodSecurityExpressionHandler,如下:

<pre class="prettyprint hljs scala" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">`public class  CustomMethodSecurityExpressionHandler  extends  DefaultMethodSecurityExpressionHandler {
    @Override
    protected MethodSecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, MethodInvocation invocation) {
        CustomSecurityExpressionRoot root = new CustomSecurityExpressionRoot(authentication);
        root.setTrustResolver(getTrustResolver());
        root.setPermissionEvaluator(getPermissionEvaluator());
        root.setRoleHierarchy(getRoleHierarchy());
        return root;
    }
}` </pre>

在 createSecurityExpressionRoot 方法中創(chuàng)建一個 CustomSecurityExpressionRoot 對象,對象的 TrustResolver、權限評估器以及角色層級等,統(tǒng)統(tǒng)都用默認的方案即可。

配置完成后,再配置一下 CustomMethodSecurityExpressionHandler 這個 Bean 即可,如下:

<pre class="prettyprint hljs scala" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">`@Bean
CustomMethodSecurityExpressionHandler customMethodSecurityExpressionHandler() {
    return new CustomMethodSecurityExpressionHandler();
}` </pre>

好啦,這就注入成功了。

接下來,我們就可以在權限注解中使用這個自定義的方法了:

<pre class="prettyprint hljs kotlin" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, &quot;Courier New&quot;, monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">`@PreAuthorize("hasPermission('system:user:add')")
public String add() {
    return "add";
}` </pre>

這個自定義權限表達式的思路,說到底還是在 Spring Security 體系中玩,個人感覺這種方式更合理一些。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容