springboot集成springsecurity jwt實現

具體項目處於特殊原因這裏不上傳了,簡單說下過程中遇到的問題,

問題一,jwt如何進行權限校驗。

首先我們在網上搜到權限處理往往都是基於hasRole進行處理的,原則上是能處理,但是業務上不規範應當使用hasPermission因此我們這裏注意(敲黑板)。使用hasPermission請自行實現

PermissionEvaluator

並將此類注入到springsecurity中

注入方式如下:

@Bean
    public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler(){
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(customPermissionEvaluator);
        return handler;
    }
// 注入自定義權限校驗器
        http.authorizeRequests().expressionHandler(webSecurityExpressionHandler());

controller中實現如下:


    @PreAuthorize("hasPermission('test','permission1')")
    @RequestMapping(value = {"/home","/index"}, method = RequestMethod.GET)
    public String home(Model model) throws NotFoundException {
        return "index";
    }

問題二、HttpSecurity中的authorizeRequests() .anyRequest().authenticated()配了啥用

對於你沒有顯示寫hasPermission的也會做攔截保護,很有必要。當然你也可以不寫。影響不大

問題三、頁面如何使用springsecurity標籤

用過shiro的人對於shiro的標籤用的很爽,此處對於security由於我們自定義了jwt模式並禁用了session因此需要做些特殊配置。

請注意(敲黑板)

使用前請參考https://github.com/thymeleaf/thymeleaf-extras-springsecurity確認你的以下jar包沒有問題:

這裏我標一下重點:

首先你需要確認你的thymeleaf的版本,

其次確認依賴項

以上基本包引入確定

第二步我們在頁面頭部加入

不用加版本號

第三步使用自定義權限(敲黑板)

<span sec:authorize= "${hasPermission('test','22')} ">
    111111111111111
    </span>

代碼得這麼寫才能調用你的自定義權限

最後注入權限校驗器(敲黑板)

 //解決靜態資源被攔截的問題
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.expressionHandler(webSecurityExpressionHandler());
    }

這個地方不僅僅能處理靜態資源,還能幹這個。。。

以上爲最近處理springsecurity的問題總結,非常感謝領導和同事的幫助。非常感謝。本人技術差如有不對還請指教謝謝!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章