Spring boot如何基于攔截器實(shí)現(xiàn)訪問(wèn)權(quán)限限制
遇到一個(gè)需求是:要為用戶設(shè)置不同的菜單、數(shù)據(jù)訪問(wèn)權(quán)限。對(duì)于一些特定類型的數(shù)據(jù),有的用戶可以看有的用戶則不可以。一開(kāi)始沒(méi)有太多思路,后來(lái)一想是不是可以把'特定類型'這個(gè)參數(shù)通過(guò)@PathVariable注解加到路徑上,這樣就可以通過(guò)攔截器攔截后,校驗(yàn)此用戶是否可以訪問(wèn)這個(gè)路徑(類型)下的數(shù)據(jù)了。
話不多說(shuō),以下為具體實(shí)踐
攔截器配置類
@Configurationpublic class UserInterceptorConfig { //為了保證IDbnetUserService提前實(shí)例化,能在userInterceptor使用 //ConditionalOnMissingBean可以保證只有一個(gè)IDbnetUserService的實(shí)例 @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)限訪問(wèn)而返回true或者false } }; }}
注冊(cè)攔截器
//注冊(cè)攔截器 @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/**
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. css代碼優(yōu)化的12個(gè)技巧2. 微信開(kāi)發(fā) 網(wǎng)頁(yè)授權(quán)獲取用戶基本信息3. 爬取今日頭條Ajax請(qǐng)求4. jsp實(shí)現(xiàn)登錄驗(yàn)證的過(guò)濾器5. 詳解瀏覽器的緩存機(jī)制6. jsp EL表達(dá)式詳解7. asp批量添加修改刪除操作示例代碼8. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法9. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))10. HTML5 Canvas繪制圖形從入門到精通
