別再用過時的方式了棚菊!全新版本Spring Security浸踩,這樣用才夠優(yōu)雅!

前不久Spring Boot 2.7.0 剛剛發(fā)布统求,Spring Security 也升級到了5.7.1 检碗。升級后發(fā)現(xiàn)据块,原來一直在用的Spring Security配置方法,居然已經(jīng)被棄用了折剃。不禁感慨技術(shù)更新真快另假,用著用著就被棄用了!今天帶大家體驗下Spring Security的最新用法怕犁,看看是不是夠優(yōu)雅边篮!

SpringBoot實(shí)戰(zhàn)電商項目mall(50k+star)地址:github.com/macrozheng/…

基本使用

我們先對比下Spring Security提供的基本功能登錄認(rèn)證,來看看新版用法是不是更好因苹。

升級版本

首先修改項目的pom.xml文件苟耻,把Spring Boot版本升級至2.7.0版本。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.0</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

舊用法

在Spring Boot 2.7.0 之前的版本中扶檐,我們需要寫個配置類繼承WebSecurityConfigurerAdapter凶杖,然后重寫Adapter中的三個方法進(jìn)行配置;

/**
 * SpringSecurity的配置
 * Created by macro on 2018/4/26.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OldSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UmsAdminService adminService;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        //省略HttpSecurity的配置
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

如果你在SpringBoot 2.7.0版本中進(jìn)行使用的話款筑,你就會發(fā)現(xiàn)WebSecurityConfigurerAdapter已經(jīng)被棄用了智蝠,看樣子Spring Security要堅決放棄這種用法了!

新用法

新用法非常簡單奈梳,無需再繼承WebSecurityConfigurerAdapter杈湾,只需直接聲明配置類,再配置一個生成SecurityFilterChainBean的方法攘须,把原來的HttpSecurity配置移動到該方法中即可漆撞。

/**
 * SpringSecurity 5.4.x以上新用法配置
 * 為避免循環(huán)依賴,僅用于配置HttpSecurity
 * Created by macro on 2022/5/19.
 */
@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        //省略HttpSecurity的配置
        return httpSecurity.build();
    }

}

新用法感覺非常簡潔干脆于宙,避免了繼承WebSecurityConfigurerAdapter并重寫方法的操作浮驳,強(qiáng)烈建議大家更新一波!

高級使用

升級 Spring Boot 2.7.0版本后捞魁,Spring Security對于配置方法有了大的更改至会,那么其他使用有沒有影響呢?其實(shí)是沒啥影響的谱俭,這里再聊聊如何使用Spring Security實(shí)現(xiàn)動態(tài)權(quán)限控制奉件!

基于方法的動態(tài)權(quán)限

首先來聊聊基于方法的動態(tài)權(quán)限控制,這種方式雖然實(shí)現(xiàn)簡單昆著,但卻有一定的弊端县貌。

  • 在配置類上使用@EnableGlobalMethodSecurity來開啟它;
/**
 * SpringSecurity的配置
 * Created by macro on 2018/4/26.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OldSecurityConfig extends WebSecurityConfigurerAdapter {

}
  • 然后在方法中使用@PreAuthorize配置訪問接口需要的權(quán)限凑懂;
/**
 * 商品管理Controller
 * Created by macro on 2018/4/26.
 */
@Controller
@Api(tags = "PmsProductController", description = "商品管理")
@RequestMapping("/product")
public class PmsProductController {
    @Autowired
    private PmsProductService productService;

    @ApiOperation("創(chuàng)建商品")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAuthority('pms:product:create')")
    public CommonResult create(@RequestBody PmsProductParam productParam, BindingResult bindingResult) {
        int count = productService.create(productParam);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }
}
  • 再從數(shù)據(jù)庫中查詢出用戶所擁有的權(quán)限值設(shè)置到UserDetails對象中去窃这,這種做法雖然實(shí)現(xiàn)方便,但是把權(quán)限值寫死在了方法上,并不是一種優(yōu)雅的做法杭攻。
/**
 * UmsAdminService實(shí)現(xiàn)類
 * Created by macro on 2018/4/26.
 */
@Service
public class UmsAdminServiceImpl implements UmsAdminService {
    @Override
    public UserDetails loadUserByUsername(String username){
        //獲取用戶信息
        UmsAdmin admin = getAdminByUsername(username);
        if (admin != null) {
            List<UmsPermission> permissionList = getPermissionList(admin.getId());
            return new AdminUserDetails(admin,permissionList);
        }
        throw new UsernameNotFoundException("用戶名或密碼錯誤");
    }
}

基于路徑的動態(tài)權(quán)限

其實(shí)每個接口對應(yīng)的路徑都是唯一的祟敛,通過路徑來進(jìn)行接口的權(quán)限控制才是更優(yōu)雅的方式。

  • 首先我們需要創(chuàng)建一個動態(tài)權(quán)限的過濾器兆解,這里注意下doFilter方法馆铁,用于配置放行OPTIONS白名單請求,它會調(diào)用super.beforeInvocation(fi)方法锅睛,此方法將調(diào)用AccessDecisionManager中的decide方法來進(jìn)行鑒權(quán)操作埠巨;
/**
 * 動態(tài)權(quán)限過濾器,用于實(shí)現(xiàn)基于路徑的動態(tài)權(quán)限過濾
 * Created by macro on 2020/2/7.
 */
public class DynamicSecurityFilter extends AbstractSecurityInterceptor implements Filter {

    @Autowired
    private DynamicSecurityMetadataSource dynamicSecurityMetadataSource;
    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Autowired
    public void setMyAccessDecisionManager(DynamicAccessDecisionManager dynamicAccessDecisionManager) {
        super.setAccessDecisionManager(dynamicAccessDecisionManager);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
        //OPTIONS請求直接放行
        if(request.getMethod().equals(HttpMethod.OPTIONS.toString())){
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
            return;
        }
        //白名單請求直接放行
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String path : ignoreUrlsConfig.getUrls()) {
            if(pathMatcher.match(path,request.getRequestURI())){
                fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
                return;
            }
        }
        //此處會調(diào)用AccessDecisionManager中的decide方法進(jìn)行鑒權(quán)操作
        InterceptorStatusToken token = super.beforeInvocation(fi);
        try {
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
        } finally {
            super.afterInvocation(token, null);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public Class<?> getSecureObjectClass() {
        return FilterInvocation.class;
    }

    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return dynamicSecurityMetadataSource;
    }

}
  • 接下來我們就需要創(chuàng)建一個類來繼承AccessDecisionManager现拒,通過decide方法對訪問接口所需權(quán)限和用戶擁有的權(quán)限進(jìn)行匹配辣垒,匹配則放行;
/**
 * 動態(tài)權(quán)限決策管理器印蔬,用于判斷用戶是否有訪問權(quán)限
 * Created by macro on 2020/2/7.
 */
public class DynamicAccessDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object object,
                       Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        // 當(dāng)接口未被配置資源時直接放行
        if (CollUtil.isEmpty(configAttributes)) {
            return;
        }
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute configAttribute = iterator.next();
            //將訪問所需資源或用戶擁有資源進(jìn)行比對
            String needAuthority = configAttribute.getAttribute();
            for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
                if (needAuthority.trim().equals(grantedAuthority.getAuthority())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("抱歉勋桶,您沒有訪問權(quán)限");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
  • 由于上面的decide方法中的configAttributes屬性是從FilterInvocationSecurityMetadataSourcegetAttributes方法中獲取的,我們還需創(chuàng)建一個類繼承它侥猬,getAttributes方法可用于獲取訪問當(dāng)前路徑所需權(quán)限值例驹;
/**
 * 動態(tài)權(quán)限數(shù)據(jù)源,用于獲取動態(tài)權(quán)限規(guī)則
 * Created by macro on 2020/2/7.
 */
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static Map<String, ConfigAttribute> configAttributeMap = null;
    @Autowired
    private DynamicSecurityService dynamicSecurityService;

    @PostConstruct
    public void loadDataSource() {
        configAttributeMap = dynamicSecurityService.loadDataSource();
    }

    public void clearDataSource() {
        configAttributeMap.clear();
        configAttributeMap = null;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        if (configAttributeMap == null) this.loadDataSource();
        List<ConfigAttribute>  configAttributes = new ArrayList<>();
        //獲取當(dāng)前訪問的路徑
        String url = ((FilterInvocation) o).getRequestUrl();
        String path = URLUtil.getPath(url);
        PathMatcher pathMatcher = new AntPathMatcher();
        Iterator<String> iterator = configAttributeMap.keySet().iterator();
        //獲取訪問該路徑所需資源
        while (iterator.hasNext()) {
            String pattern = iterator.next();
            if (pathMatcher.match(pattern, path)) {
                configAttributes.add(configAttributeMap.get(pattern));
            }
        }
        // 未設(shè)置操作請求權(quán)限退唠,返回空集合
        return configAttributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
  • 這里需要注意的是鹃锈,所有路徑對應(yīng)的權(quán)限值數(shù)據(jù)來自于自定義的DynamicSecurityService
/**
 * 動態(tài)權(quán)限相關(guān)業(yè)務(wù)類
 * Created by macro on 2020/2/7.
 */
public interface DynamicSecurityService {
    /**
     * 加載資源ANT通配符和資源對應(yīng)MAP
     */
    Map<String, ConfigAttribute> loadDataSource();
}
  • 一切準(zhǔn)備就緒瞧预,把動態(tài)權(quán)限過濾器添加到FilterSecurityInterceptor之前屎债;
/**
 * SpringSecurity 5.4.x以上新用法配置
 * 為避免循環(huán)依賴,僅用于配置HttpSecurity
 * Created by macro on 2022/5/19.
 */
@Configuration
public class SecurityConfig {

    @Autowired
    private DynamicSecurityService dynamicSecurityService;
    @Autowired
    private DynamicSecurityFilter dynamicSecurityFilter;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        //省略若干配置...
        //有動態(tài)權(quán)限配置時添加動態(tài)權(quán)限校驗過濾器
        if(dynamicSecurityService!=null){
            registry.and().addFilterBefore(dynamicSecurityFilter, FilterSecurityInterceptor.class);
        }
        return httpSecurity.build();
    }

}
/**
 * mall-security模塊相關(guān)配置
 * 自定義配置檀咙,用于配置如何獲取用戶信息及動態(tài)權(quán)限
 * Created by macro on 2022/5/20.
 */
@Configuration
public class MallSecurityConfig {

    @Autowired
    private UmsAdminService adminService;

    @Bean
    public UserDetailsService userDetailsService() {
        //獲取登錄用戶信息
        return username -> {
            AdminUserDetails admin = adminService.getAdminByUsername(username);
            if (admin != null) {
                return admin;
            }
            throw new UsernameNotFoundException("用戶名或密碼錯誤");
        };
    }

    @Bean
    public DynamicSecurityService dynamicSecurityService() {
        return new DynamicSecurityService() {
            @Override
            public Map<String, ConfigAttribute> loadDataSource() {
                Map<String, ConfigAttribute> map = new ConcurrentHashMap<>();
                List<UmsResource> resourceList = adminService.getResourceList();
                for (UmsResource resource : resourceList) {
                    map.put(resource.getUrl(), new org.springframework.security.access.SecurityConfig(resource.getId() + ":" + resource.getName()));
                }
                return map;
            }
        };
    }

}

效果測試

  • 接下來啟動我們的示例項目mall-tiny-security,使用如下賬號密碼登錄璃诀,該賬號只配置了訪問/brand/listAll的權(quán)限弧可,訪問地址:http://localhost:8088/swagger-ui/
  • 然后把返回的token放入到Swagger的認(rèn)證頭中;
  • 當(dāng)我們訪問有權(quán)限的接口時可以正常獲取到數(shù)據(jù)劣欢;
  • 當(dāng)我們訪問沒有權(quán)限的接口時棕诵,返回沒有訪問權(quán)限的接口提示裁良。

總結(jié)

Spring Security的升級用法確實(shí)夠優(yōu)雅,夠簡單校套,而且對之前用法的兼容性也比較好价脾!個人感覺一個成熟的框架不太會在升級過程中大改用法,即使改了也會對之前的用法做兼容笛匙,所以對于絕大多數(shù)框架來說舊版本會用侨把,新版本照樣會用!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末妹孙,一起剝皮案震驚了整個濱河市秋柄,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蠢正,老刑警劉巖骇笔,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異机隙,居然都是意外死亡蜘拉,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進(jìn)店門有鹿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來旭旭,“玉大人,你說我怎么就攤上這事葱跋〕旨模” “怎么了?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵娱俺,是天一觀的道長稍味。 經(jīng)常有香客問我,道長荠卷,這世上最難降的妖魔是什么模庐? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮油宜,結(jié)果婚禮上掂碱,老公的妹妹穿的比我還像新娘。我一直安慰自己慎冤,他們只是感情好疼燥,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蚁堤,像睡著了一般醉者。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天撬即,我揣著相機(jī)與錄音立磁,去河邊找鬼。 笑死搞莺,一個胖子當(dāng)著我的面吹牛息罗,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播才沧,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼迈喉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了温圆?” 一聲冷哼從身側(cè)響起挨摸,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎岁歉,沒想到半個月后得运,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡锅移,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年熔掺,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片非剃。...
    茶點(diǎn)故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡置逻,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出备绽,到底是詐尸還是另有隱情券坞,我是刑警寧澤,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布肺素,位于F島的核電站恨锚,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏倍靡。R本人自食惡果不足惜猴伶,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望塌西。 院中可真熱鬧他挎,春花似錦、人聲如沸雨让。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽栖忠。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間庵寞,已是汗流浹背狸相。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留捐川,地道東北人脓鹃。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像古沥,于是被迫代替她去往敵國和親瘸右。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容