电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

Spring Security 多過濾鏈的使用詳解

瀏覽:4日期:2023-07-03 09:40:59
目錄一、背景二、需求1、給客戶端使用的api2、給網站使用的api三、實現方案方案一:方案二四、實現1、app 端 Spring Security 的配置五、實現效果1、app 有權限訪問 api2、app 無權限訪問 api3、admin 用戶有權限訪問 網站 api4、dev 用戶無權限訪問 網站 api六、完整代碼一、背景

在我們實際的開發過程中,有些時候可能存在這么一些情況,某些api 比如: /api/** 這些是給App端使用的,數據的返回都是以JSON的格式返回,且這些API的認證方式都是使用的TOKEN進行認證。而除了 /api/** 這些API之外,都是給網頁端使用的,需要使用表單認證,給前端返回的都是某個頁面。

二、需求1、給客戶端使用的api 攔截 /api/**所有的請求。 /api/**的所有請求都需要ROLE_ADMIN的角色。 從請求頭中獲取 token,只要獲取到token的值,就認為認證成功,并賦予ROLE_ADMIN到角色。 如果沒有權限,則給前端返回JSON對象 {message:'您無權限訪問'} 訪問 /api/userInfo端點 請求頭攜帶 token 可以訪問。請求頭不攜帶token不可以訪問。2、給網站使用的api 攔截 所有的請求,但是不處理/api/**開頭的請求。 所有的請求需要ROLE_ADMIN的權限。 沒有權限,需要使用表單登錄。 登錄成功后,訪問了無權限的請求,直接跳轉到百度去。 構建2個內建的用戶 用戶一: admin/admin 擁有 ROLE_ADMIN 角色用戶二:dev/dev 擁有 ROLE_DEV 角色 訪問 /index 端點 admin 用戶訪問,可以訪問。dev 用戶訪問,不可以訪問,權限不夠。三、實現方案方案一:

直接拆成多個服務,其中 /api/** 的成為一個服務。非/api/**的拆成另外一個服務。各個服務使用自己的配置,互不影響。

方案二

在同一個服務中編寫。不同的請求使用不同的SecurityFilterChain來實現。

經過考慮,此處采用方案二來實現,因為方案一簡單,使用方案二實現,也可以記錄下在同一個項目中 通過使用多條過濾器鏈,因為并不是所有的時候,都是可以分成多個項目的。

擴展:

1、Spring Security SecurityFilterChain 的結構

Spring Security 多過濾鏈的使用詳解

2、控制 SecurityFilterChain 的執行順序

使用 org.springframework.core.annotation.Order 注解。

3、查看是怎樣選擇那個 SecurityFilterChain 的

查看 org.springframework.web.filter.DelegatingFilterProxy#doFilter方法

四、實現1、app 端 Spring Security 的配置

package com.huan.study.security.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.annotation.Order;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.security.authentication.TestingAuthenticationToken;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.core.Authentication;import org.springframework.security.core.authority.AuthorityUtils;import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.security.web.SecurityFilterChain;import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;import org.springframework.util.StringUtils;import javax.servlet.http.HttpServletRequest;import java.nio.charset.StandardCharsets;/** * 給 app 端用的 Security 配置 * * @author huan.fu 2021/7/13 - 下午9:06 */@Configurationpublic class AppSecurityConfig { /** * 處理 給 app(前后端分離) 端使用的過濾鏈 * 以 json 的數據格式返回給前端 */ @Bean @Order(1) public SecurityFilterChain appSecurityFilterChain(HttpSecurity http) throws Exception {// 只處理 /api 開頭的請求return http.antMatcher('/api/**').authorizeRequests()// 所有以 /api 開頭的請求都需要 ADMIN 的權限 .antMatchers('/api/**') .hasRole('ADMIN') .and()// 捕獲到異常,直接給前端返回 json 串.exceptionHandling() .authenticationEntryPoint((request, response, authException) -> {response.setStatus(HttpStatus.UNAUTHORIZED.value());response.setCharacterEncoding(StandardCharsets.UTF_8.name());response.setContentType(MediaType.APPLICATION_JSON.toString());response.getWriter().write('{'message:':'您無權訪問01'}'); }) .accessDeniedHandler((request, response, accessDeniedException) -> {response.setStatus(HttpStatus.UNAUTHORIZED.value());response.setCharacterEncoding(StandardCharsets.UTF_8.name());response.setContentType(MediaType.APPLICATION_JSON.toString());response.getWriter().write('{'message:':'您無權訪問02'}'); }) .and()// 用戶認證.addFilterBefore((request, response, chain) -> { // 此處可以模擬從 token 中解析出用戶名、權限等 String token = ((HttpServletRequest) request).getHeader('token'); if (!StringUtils.hasText(token)) {chain.doFilter(request, response);return; } Authentication authentication = new TestingAuthenticationToken(token, null, AuthorityUtils.createAuthorityList('ROLE_ADMIN')); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(request, response);}, UsernamePasswordAuthenticationFilter.class).build(); }}

2、網站端 Spring Secuirty 的配置

package com.huan.study.security.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.annotation.Order;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;import org.springframework.security.core.authority.AuthorityUtils;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.web.SecurityFilterChain;/** * 給 網站 應用的安全配置 * * @author huan.fu 2021/7/14 - 上午9:09 */@Configurationpublic class WebSiteSecurityFilterChainConfig { /** * 處理 給 webSite(非前后端分離) 端使用的過濾鏈 * 以 頁面 的格式返回給前端 */ @Bean @Order(2) public SecurityFilterChain webSiteSecurityFilterChain(HttpSecurity http) throws Exception {AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);// 創建用戶authenticationManagerBuilder.inMemoryAuthentication().withUser('admin') .password(new BCryptPasswordEncoder().encode('admin')) .authorities(AuthorityUtils.commaSeparatedStringToAuthorityList('ROLE_ADMIN')) .and().withUser('dev') .password(new BCryptPasswordEncoder().encode('dev')) .authorities(AuthorityUtils.commaSeparatedStringToAuthorityList('ROLE_DEV')) .and().passwordEncoder(new BCryptPasswordEncoder());// 只處理 所有 開頭的請求return http.antMatcher('/**').authorizeRequests()// 所有請求都必須要認證才可以訪問 .anyRequest() .hasRole('ADMIN') .and()// 禁用csrf.csrf() .disable()// 啟用表單登錄.formLogin() .permitAll() .and()// 捕獲成功認證后無權限訪問異常,直接跳轉到 百度.exceptionHandling() .accessDeniedHandler((request, response, exception) -> {response.sendRedirect('http://www.baidu.com'); }) .and().build(); } /** * 忽略靜態資源 */ @Bean public WebSecurityCustomizer webSecurityCustomizer( ){return web -> web.ignoring().antMatchers('/**/js/**').antMatchers('/**/css/**'); }}

3、控制器寫法

/** * 資源控制器 * * @author huan.fu 2021/7/13 - 下午9:33 */@Controllerpublic class ResourceController { /** * 返回用戶信息 */ @GetMapping('/api/userInfo') @ResponseBody public Authentication showUserInfoApi() {return SecurityContextHolder.getContext().getAuthentication(); } @GetMapping('/index') public String index(Model model){model.addAttribute('username','張三');return 'index'; }}

4、引入jar包

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>五、實現效果1、app 有權限訪問 api

Spring Security 多過濾鏈的使用詳解

2、app 無權限訪問 api

Spring Security 多過濾鏈的使用詳解

3、admin 用戶有權限訪問 網站 api

Spring Security 多過濾鏈的使用詳解

4、dev 用戶無權限訪問 網站 api

Spring Security 多過濾鏈的使用詳解

訪問無權限的API直接跳轉到 百度 首頁。

六、完整代碼

https://gitee.com/huan1993/Spring-Security/tree/master/multi-security-filter-chain

到此這篇關于Spring Security 多過濾鏈的使用詳解的文章就介紹到這了,更多相關Spring Security 多過濾鏈 內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 临朐空调移机_空调维修「空调回收」临朐二手空调 | 仪器仪表网 - 永久免费的b2b电子商务平台 | crm客户关系管理系统,销售管理系统,crm系统,在线crm,移动crm系统 - 爱客crm | 影像测量仪_三坐标测量机_一键式二次元_全自动影像测量仪-广东妙机精密科技股份有限公司 | 耐热钢-耐磨钢-山东聚金合金钢铸造有限公司 | 磁力抛光机_磁力研磨机_磁力去毛刺机_精密五金零件抛光设备厂家-冠古科技 | 大学食堂装修设计_公司餐厅效果图_工厂食堂改造_迈普装饰 | 耐热钢-耐磨钢-山东聚金合金钢铸造有限公司 | 专注氟塑料泵_衬氟泵_磁力泵_卧龙泵阀_化工泵专业品牌 - 梭川泵阀 | 超声波清洗机_大型超声波清洗机_工业超声波清洗设备-洁盟清洗设备 | 双工位钻铣攻牙机-转换工作台钻攻中心-钻铣攻牙机一体机-浙江利硕自动化设备有限公司 | 政府回应:200块在义乌小巷能买到爱情吗?——揭秘打工族省钱约会的生存智慧 | 高考志愿规划师_高考规划师_高考培训师_高报师_升学规划师_高考志愿规划师培训认证机构「向阳生涯」 | 雨水收集系统厂家-雨水收集利用-模块雨水收集池-徐州博智环保科技有限公司 | 精雕机-火花机-精雕机 cnc-高速精雕机-电火花机-广东鼎拓机械科技有限公司 | 艺术漆十大品牌_艺术涂料加盟代理_蒙太奇艺术涂料厂家品牌|艺术漆|微水泥|硅藻泥|乳胶漆 | 慈溪麦田广告公司,提供慈溪广告设计。 | [官网]叛逆孩子管教_戒网瘾学校_全封闭问题青少年素质教育_新起点青少年特训学校 | 卫生型双针压力表-高温防腐差压表-安徽康泰电气有限公司 | 上海小程序开发-上海小程序制作公司-上海网站建设-公众号开发运营-软件外包公司-咏熠科技 | 2025福建平潭岛旅游攻略|蓝眼泪,景点,住宿攻略-趣平潭网 | 郑州宣传片拍摄-TVC广告片拍摄-微电影短视频制作-河南优柿文化传媒有限公司 | 减速机电机一体机_带电机减速器一套_德国BOSERL电动机与减速箱生产厂家 | 真空泵维修保养,普发,阿尔卡特,荏原,卡西亚玛,莱宝,爱德华干式螺杆真空泵维修-东莞比其尔真空机电设备有限公司 | 长沙广告公司_制作,长沙喷绘_发光字_招牌制作_长沙泓润广告官网 长城人品牌官网 | 移动机器人产业联盟官网| 应急灯_消防应急灯_应急照明灯_应急灯厂家-大成智慧官网 | 磁力抛光研磨机_超声波清洗机厂家_去毛刺设备-中锐达数控 | 急救箱-应急箱-急救包厂家-北京红立方医疗设备有限公司 | 南京雕塑制作厂家-不锈钢雕塑制作-玻璃钢雕塑制作-先登雕塑厂 | 电机修理_二手电机专家-河北豫通机电设备有限公司(原石家庄冀华高压电机维修中心) | 蓝牙音频分析仪-多功能-四通道-八通道音频分析仪-东莞市奥普新音频技术有限公司 | 定量包装秤,吨袋包装称,伸缩溜管,全自动包装秤,码垛机器人,无锡市邦尧机械工程有限公司 | 闪电优家-卫生间防水补漏_酒店漏水渗水维修_防水堵漏公司 | 水环真空泵厂家,2bv真空泵,2be真空泵-淄博真空设备厂 | 代理记账_免费注册公司_营业执照代办_资质代办-【乐财汇】 | 陕西视频监控,智能安防监控,安防系统-西安鑫安5A安防工程公司 | ALC墙板_ALC轻质隔墙板_隔音防火墙板_轻质隔墙材料-湖北博悦佳 | 上海质量认证办理中心| 体感VRAR全息沉浸式3D投影多媒体展厅展会游戏互动-万展互动 | 全自动翻转振荡器-浸出式水平振荡器厂家-土壤干燥箱价格-常州普天仪器 |