您好,登錄后才能下訂單哦!
這篇文章運用簡單易懂的例子給大家介紹Spring boot使用攔截器實現(xiàn)訪問權(quán)限限制,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
遇到一個需求是:要為用戶設(shè)置不同的菜單、數(shù)據(jù)訪問權(quán)限。對于一些特定類型的數(shù)據(jù),有的用戶可以看有的用戶則不可以。一開始沒有太多思路,后來一想是不是可以把"特定類型"這個參數(shù)通過@PathVariable注解加到路徑上,這樣就可以通過攔截器攔截后,校驗此用戶是否可以訪問這個路徑(類型)下的數(shù)據(jù)了。
話不多說,以下為具體實踐
攔截器配置類
@Configuration public class UserInterceptorConfig { //為了保證IDbnetUserService提前實例化,能在userInterceptor使用 //ConditionalOnMissingBean可以保證只有一個IDbnetUserService的實例 @Bean @ConditionalOnMissingBean(IDbnetUserService.class) public IDbnetUserService dbnetUserService() { return new DbnetUserServiceImpl(); } //攔截器 @Bean(name = "userInterceptor") public HandlerInterceptor userInterceptor(IDbnetUserService dbnetUserService) { return new HandlerInterceptor() { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //url = request.getRequestURI() 判斷url是否可以有權(quán)限訪問而返回true或者false } }; } }
注冊攔截器
//注冊攔截器 @Bean public WebMvcConfigurer registerInterceptor(@Qualifier("userInterceptor") HandlerInterceptor userInterceptor) { return new WebMvcConfigurerAdapter() { @Override public void addInterceptors(InterceptorRegistry registry) { //要攔截的路徑 List<String> path = interceptorProperties.getPath(); //要排除的路徑 List<String> excludePath = interceptorProperties.getExcludePath(); registry.addInterceptor(userInterceptor).addPathPatterns(path.stream().toArray(String[]::new)) .excludePathPatterns(excludePath.stream().toArray(String[]::new)); } }; }
配置要攔截的路徑
@Component @ConfigurationProperties(prefix = "dbnet.interceptor") public class InterceptorProperties { /** * 需要攔截的接口通配 */ private List<String> path = new ArrayList<>(); /** * 需要忽略的接口通配 */ private List<String> excludePath = new ArrayList<>(); public List<String> getPath() { return path; } public void setPath(List<String> path) { this.path = path; } public List<String> getExcludePath() { return excludePath; } public void setExcludePath(List<String> excludePath) { this.excludePath = excludePath; } }
dbnet: interceptor: path: /dbnet/**,/datanet/** excludePath: /dbnet/detail,/datanet/recommend,/datanet/count,/datanet/getKeys,/datenet/metadata/**
關(guān)于Spring boot使用攔截器實現(xiàn)訪問權(quán)限限制就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。