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

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

Spring Boot構建系統安全層的步驟

瀏覽:3日期:2023-07-16 17:19:43
01 | Spring Security 架構及核心類Spring Security 中的過濾器鏈

Spring Security 中采用的是管道-過濾器(Pipe-Filter)架構模式,這些過濾器鏈,構成了 Spring Security 的核心。如下圖所示:

Spring Boot構建系統安全層的步驟

項目一旦啟動,過濾器鏈將會實現自動配置,如下圖所示:

Spring Boot構建系統安全層的步驟

UsernamePasswordAuthenticationFilter 用來檢查輸入的用戶名和密碼,代碼如下:

public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException {if (postOnly && !request.getMethod().equals('POST')) { throw new AuthenticationServiceException('Authentication method not supported: ' + request.getMethod());} String username = obtainUsername(request);String password = obtainPassword(request); if (username == null) { username = '';} if (password == null) { password = '';} username = username.trim(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);// Allow subclasses to set the 'details' propertysetDetails(request, authRequest);return this.getAuthenticationManager().authenticate(authRequest); } …}

BasicAuthenticationFilter 用來認證用戶的身份。

FilterSecurityInterceptor 用來判定該請求是否能夠訪問目標 HTTP 端點。

Spring Security 中的核心類

Spring Boot構建系統安全層的步驟

SecurityContextHolder 存儲了應用的安全上下文對象 SecurityContext,包含系統請求中最近使用的認證信息。

一個 HTTP 請求到達系統后,將通過一系列的 Filter 完成用戶認證,然后具體的工作交由 AuthenticationManager 完成,AuthenticationManager 成功驗證后會返回填充好的 Authentication 實例。

AuthenticationManager 是一個接口,其實現類 ProviderManager 會進一步依賴 AuthenticationProvider 接口完成具體的認證工作。

在 Spring Security 中存在一大批 AuthenticationProvider 接口的實現類,分別完成各種認證操作。在執行具體的認證工作時,Spring Security 勢必會使用用戶詳細信息,UserDetailsService 服務就是用來對用戶詳細信息實現管理。

02 | 基于 Spring Security 構建用戶認證體系

在 Spring Boot 中整合 Spring Security 框架首先需要引入依賴:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>

只要我們在代碼工程中添加了上述依賴,包含在該工程中的所有 HTTP 端點都將被保護起來。

在引入 spring-boot-starter-security 依賴之后,Spring Security 會默認創建一個用戶名為“user”的賬號。當我們訪問 AccountController 的 “accounts/{accountId}” 端點時,彈出如下界面:

Spring Boot構建系統安全層的步驟

同時,控制臺日志打印如下:

Using generated security password: 17bbf7c4-456a-48f5-a12e-a680066c8f80

因此,訪問該接口需要設置如下信息:

Spring Boot構建系統安全層的步驟

每次啟動應用時,通過 Spring Security 自動生成的密碼都會有所變化。如果我們想設置登錄賬號和密碼,可以在 application.yml 中配置如下:

spring: security: user: name: springcss password: springcss_password配置 Spring Security

初始化用戶信息所依賴的配置類是 WebSecurityConfigurer 接口,在日常開發中,我們往往是使用 WebSecurityConfigurerAdapter 類并覆寫其中的 configure(AuthenticationManagerBuilder auth) 的方法完成配置工作。

使用 AuthenticationManagerBuilder 類創建一個 AuthenticationManager 就能夠輕松實現基于內存、LADP 和 JDBC 的驗證。初始化所使用的用戶信息只需要指定用戶名(Username)、密碼(Password)和角色(Role)這三項數據即可。

使用基于內存的用戶信息存儲方案

@Overrideprotected void configure(AuthenticationManagerBuilder builder) throws Exception { builder.inMemoryAuthentication().withUser('springcss_user').password('password1')// 或者使用.authorities('ROLE_USER').roles('USER').and().withUser('springcss_admin').password('password2').roles('USER', 'ADMIN');}

使用基于數據庫的用戶信息存儲方案

表結構如下:

create table users( username varchar_ignorecase(50) not null primary key, password varchar_ignorecase(500) not null, enabled boolean not null); create table authorities ( username varchar_ignorecase(50) not null, authority varchar_ignorecase(50) not null, constraint fk_authorities_users foreign key(username) references users(username)); create unique index ix_auth_username on authorities (username,authority);

Spring Security 的配置代碼如下:

@AutowiredDataSource dataSource; @Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery('select username, password, enabled from Users where username=?').authoritiesByUsernameQuery('select username, authority from UserAuthorities where username=?').passwordEncoder(new BCryptPasswordEncoder());}實現定制化用戶認證方案

擴展 UserDetails

public class SpringCssUser implements UserDetails { private static final long serialVersionUID = 1L; private Long id; private final String username; private final String password; private final String phoneNumber; // 省略getter/setter // 省略重寫方法}

擴展 UserDetailsService

@Servicepublic class SpringCssUserDetailsService implements UserDetailsService { @Autowired private SpringCssUserRepository repository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {SpringCssUser user = repository.findByUsername(username);if (user != null) { return user;}throw new UsernameNotFoundException('SpringCSS User ’' + username + '’ not found'); }}

整合定制化配置

@Configurationpublic class SpringCssSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired SpringCssUserDetailsService springCssUserDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(springCssUserDetailsService); }}03 | 基于 Spring Security 實現安全訪問

在日常開發過程中,我們需要對 Web 應用中的不同 HTTP 端點進行不同粒度的權限控制。

對 HTTP 端點進行訪問授權管理

使用配置方法

配置方法也是位于 WebSecurityConfigurerAdapter 類中,但使用的是 configure(HttpSecurity http) 方法,如下代碼所示:

protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()// 所有請求都需要認證.anyRequest()// 允許認證用戶訪問.authenticated().and()// 需要使用表單進行登錄.formLogin().and()// 使用 HTTP Basic Authentication 方法完成認證.httpBasic();}

Spring Security 還提供了一個 access() 方法,允許開發人員傳入一個表達式進行更細粒度的權限控制,這里,我們將引入Spring 框架提供的一種動態表達式語言—— SpEL(Spring Expression Language 的簡稱)。

只要 SpEL 表達式的返回值為 true,access() 方法就允許用戶訪問,如下代碼所示:

@Overridepublic void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers('/orders').access('hasRole(’ROLE_USER’)');}

使用注解Spring Security 提供了 @PreAuthorize 注解也可以實現類似的效果,使用該注解代碼如下所示:

@RestController@RequestMapping(value='orders')public class OrderController { @PostMapping(value = '/') @PreAuthorize('hasRole(ROLE_ADMIN)') public void addOrder(@RequestBody Order order) {… }}

@PostAuthorize 主要用于請求結束之后檢查權限。

實現多維度訪問授權方案

使用用戶級別保護服務訪問該級別是最基本的資源保護級別,只要是認證用戶就可能訪問服務內的各種資源。

@Configurationpublic class SpringCssSecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests() .anyRequest() .authenticated(); }}

使用用戶+角色級別保護服務訪問該級別在認證用戶級別的基礎上,還要求用戶屬于某一個或多個特定角色。

@Configurationpublic class SpringCssSecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers('/customers/**') .hasRole('ADMIN') .anyRequest() .authenticated(); }}

上述代碼表示只有'ADMIN'角色的認證用戶才能訪問以'/customers/'為根地址的所有 URL。

使用用戶+角色+操作級別保護服務訪問該級別在認證用戶+角色級別的基礎上,對某些 HTTP 操作方法做了訪問限制。

@Configurationpublic class SpringCssSecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception{http.authorizeRequests().antMatchers(HttpMethod.DELETE, '/customers/**').hasRole('ADMIN').anyRequest().authenticated(); }}

上述代碼的效果在于對“/customers”端點執行刪除操作時,我們需要使用具有“ADMIN”角色的“springcss_admin”用戶,否則會出現“access_denied”錯誤信息。

以上就是Spring Boot構建系統安全層的步驟的詳細內容,更多關于Spring Boot構建系統安全層的資料請關注好吧啦網其它相關文章!

標簽: Spring
相關文章:
主站蜘蛛池模板: 除甲醛公司-甲醛检测治理-杭州创绿家环保科技有限公司-室内空气净化十大品牌 | 注塑机-压铸机-塑料注塑机-卧式注塑机-高速注塑机-单缸注塑机厂家-广东联升精密智能装备科技有限公司 | 防火板_饰面耐火板价格、厂家_品牌认准格林雅 | 圣才学习网-考研考证学习平台,提供万种考研考证电子书、题库、视频课程等考试资料 | 回收二手冲床_金丰旧冲床回收_协易冲床回收 - 大鑫机械设备 | 鲸鱼视觉 -数字展厅多媒体互动展示制作公司| 挤出机_橡胶挤出机_塑料挤出机_胶片冷却机-河北伟源橡塑设备有限公司 | 全自动在线分板机_铣刀式在线分板机_曲线分板机_PCB分板机-东莞市亿协自动化设备有限公司 | 找培训机构_找学习课程_励普教育 | 自清洗过滤器_全自动过滤器_全自动反冲洗过滤器_量子过滤器-滑漮滴 | 哲力实业_专注汽车涂料汽车漆研发生产_汽车漆|修补油漆品牌厂家 长沙一级消防工程公司_智能化弱电_机电安装_亮化工程专业施工承包_湖南公共安全工程有限公司 | 塑钢件_塑钢门窗配件_塑钢配件厂家-文安县启泰金属制品有限公司 深圳南财多媒体有限公司介绍 | 手术室净化装修-手术室净化工程公司-华锐手术室净化厂家 | 1000帧高速摄像机|工业高速相机厂家|科天健光电技术 | 回转支承-转盘轴承-回转驱动生产厂家-洛阳隆达轴承有限公司 | 合肥地磅_合肥数控切割机_安徽地磅厂家_合肥世佳电工设备有限公司 | 中国产业发展研究网 - 提供行业研究报告 可行性研究报告 投资咨询 市场调研服务 | 预制舱-电力集装箱预制舱-模块化预制舱生产厂家-腾达电器设备 | 伟秀电气有限公司-10kv高低压开关柜-高低压配电柜-中置柜-充气柜-欧式箱变-高压真空断路器厂家 | 气弹簧定制-气动杆-可控气弹簧-不锈钢阻尼器-工业气弹簧-可调节气弹簧厂家-常州巨腾气弹簧供应商 | 天津货架厂_穿梭车货架_重型仓储货架_阁楼货架定制-天津钢力仓储货架生产厂家_天津钢力智能仓储装备 | 急救箱-应急箱-急救包厂家-北京红立方医疗设备有限公司 | 广州展览设计公司_展台设计搭建_展位设计装修公司-众派展览装饰 广州展览制作工厂—[优简]直营展台制作工厂_展会搭建资质齐全 | 电磁辐射仪-电磁辐射检测仪-pm2.5检测仪-多功能射线检测仪-上海何亦仪器仪表有限公司 | 厚壁钢管-厚壁无缝钢管-小口径厚壁钢管-大口径厚壁钢管 - 聊城宽达钢管有限公司 | 硫化罐-电加热蒸汽硫化罐生产厂家-山东鑫泰鑫智能装备有限公司 | 垃圾处理设备_餐厨垃圾处理设备_厨余垃圾处理设备_果蔬垃圾处理设备-深圳市三盛环保科技有限公司 | 碳化硅,氮化硅,冰晶石,绢云母,氟化铝,白刚玉,棕刚玉,石墨,铝粉,铁粉,金属硅粉,金属铝粉,氧化铝粉,硅微粉,蓝晶石,红柱石,莫来石,粉煤灰,三聚磷酸钠,六偏磷酸钠,硫酸镁-皓泉新材料 | 环氧铁红防锈漆_环氧漆_无溶剂环氧涂料_环氧防腐漆-华川涂料 | 爱佩恒温恒湿测试箱|高低温实验箱|高低温冲击试验箱|冷热冲击试验箱-您身边的模拟环境试验设备技术专家-合作热线:400-6727-800-广东爱佩试验设备有限公司 | 西子馋火锅鸡加盟-太原市龙城酉鼎餐饮管理有限公司 | PCB厂|线路板厂|深圳线路板厂|软硬结合板厂|电路板生产厂家|线路板|深圳电路板厂家|铝基板厂家|深联电路-专业生产PCB研发制造 | 污水处理设备,一体化泵站,一体化净水设备-「梦之洁环保设备厂家」 | 铁艺,仿竹,竹节,护栏,围栏,篱笆,栅栏,栏杆,护栏网,网围栏,厂家 - 河北稳重金属丝网制品有限公司 山东太阳能路灯厂家-庭院灯生产厂家-济南晟启灯饰有限公司 | 冻干机(冷冻干燥机)_小型|实验型|食品真空冷冻干燥机-松源 | 柴油机_柴油发电机_厂家_品牌-江苏卡得城仕发动机有限公司 | 防勒索软件_数据防泄密_Trellix(原McAfee)核心代理商_Trellix(原Fireeye)售后-广州文智信息科技有限公司 | 滑板场地施工_极限运动场地设计_滑板公园建造_盐城天人极限运动场地建设有限公司 | 安徽合肥项目申报咨询公司_安徽合肥高新企业项目申报_安徽省科技项目申报代理 | 陕西自考报名_陕西自学考试网| 三氯异氰尿酸-二氯-三氯-二氯异氰尿酸钠-优氯净-强氯精-消毒片-济南中北_优氯净厂家 |