Spring Security權(quán)限控制框架使用指南
Feb 18, 2024 pm 05:00 PM在背景管理系統(tǒng)中,通常需要存取權(quán)限控制,以限制不同使用者對介面的存取能力。如果使用者缺乏特定權(quán)限,則無法存取某些介面。
本文將用 waynboot-mall 專案舉例,為大家介紹常見後管系統(tǒng)如何引入權(quán)限控制框架 Spring Security。大綱如下:
waynboot-mall 專案網(wǎng)址:https://github.com/wayn111/waynboot-mall
一、什麼是 Spring Security
Spring Security 是一個基於 Spring 框架的開源項目,旨在為 Java 應(yīng)用程式提供強大且靈活的安全解決方案。 Spring Security 提供了以下特性:
- 認證:支援多種認證機制,如表單登入、HTTP 基本認證、OAuth2、OpenID 等。
- 授權(quán):支援基於角色或權(quán)限的存取控制,以及基於表達式的細粒度控制。
- 防護:提供了多種防護措施,例如防止會話固定、點擊劫持、跨站請求偽造等攻擊。
- 整合:與 Spring 框架和其他第三方程式庫和框架進行無縫集成,如 Spring MVC、Thymeleaf、Hibernate 等。
二、如何引進 Spring Security
在 waynboot-mall 專案中直接引入 spring-boot-starter-security 依賴,
org.springframework.boot spring-boot-starter-security 3.1.0
三、如何設(shè)定 Spring Security
在 Spring Security 3.0 中要設(shè)定 Spring Security 跟以往是有些不同的,例如不在繼承 WebSecurityConfigurerAdapter。在 waynboot-mall 專案中,具體配置如下,
@Configuration @EnableWebSecurity @AllArgsConstructor @EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true) public class SecurityConfig { private UserDetailsServiceImpl userDetailsService; private AuthenticationEntryPointImpl unauthorizedHandler; private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; private LogoutSuccessHandlerImpl logoutSuccessHandler; @Bean public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { httpSecurity // cors啟用 .cors(httpSecurityCorsConfigurer -> {}) .csrf(AbstractHttpConfigurer::disable) .sessionManagement(httpSecuritySessionManagementConfigurer -> { httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS); }) .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> { httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint(unauthorizedHandler); }) // 過濾請求 .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> { authorizationManagerRequestMatcherRegistry .requestMatchers("/favicon.ico", "/login", "/favicon.ico", "/actuator/**").anonymous() .requestMatchers("/slider/**").anonymous() .requestMatchers("/captcha/**").anonymous() .requestMatchers("/upload/**").anonymous() .requestMatchers("/common/download**").anonymous() .requestMatchers("/doc.html").anonymous() .requestMatchers("/swagger-ui/**").anonymous() .requestMatchers("/swagger-resources/**").anonymous() .requestMatchers("/webjars/**").anonymous() .requestMatchers("/*/api-docs").anonymous() .requestMatchers("/druid/**").anonymous() .requestMatchers("/elastic/**").anonymous() .requestMatchers("/message/**").anonymous() .requestMatchers("/ws/**").anonymous() // 除上面外的所有請求全部需要鑒權(quán)認證 .anyRequest().authenticated(); }) .headers(httpSecurityHeadersConfigurer -> { httpSecurityHeadersConfigurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable); }); // 處理跨域請求中的Preflight請求(cors),設(shè)置corsConfigurationSource后無需使用 // .requestMatchers(CorsUtils::isPreFlightRequest).permitAll() // 對于登錄login 驗證碼captchaImage 允許匿名訪問 httpSecurity.logout(httpSecurityLogoutConfigurer -> { httpSecurityLogoutConfigurer.logoutUrl("/logout"); httpSecurityLogoutConfigurer.logoutSuccessHandler(logoutSuccessHandler); }); // 添加JWT filter httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); // 認證用戶時用戶信息加載配置,注入springAuthUserService httpSecurity.userDetailsService(userDetailsService); return httpSecurity.build(); } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); } /** * 強散列哈希加密實現(xiàn) */ @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } }
這裡詳細介紹下 SecurityConfig 設(shè)定類別:
- filterChain(HttpSecurity httpSecurity) 方法是存取控制的核??心方法,這裡面可以針對 url 設(shè)定是否需要權(quán)限認證、cors 設(shè)定、csrf 設(shè)定、使用者資訊載入設(shè)定、jwt 過濾器攔截設(shè)定等眾多功能。
- authenticationManager(AuthenticationConfiguration authenticationConfiguration) 方法適用於啟用認證接口,需要手動聲明,否則啟動報錯。
- bCryptPasswordEncoder() 方法使用者定義使用者登入時的密碼加密策略,需要手動聲明,否則啟動報錯。
四、如何使用 Spring Security
要使用 Spring Security,只需要在需要控制存取權(quán)的方法或類別上新增對應(yīng)的 @PreAuthorize 註解即可,如下,
@Slf4j @RestController @AllArgsConstructor @RequestMapping("system/role") public class RoleController extends BaseController { private IRoleService iRoleService; @PreAuthorize("@ss.hasPermi('system:role:list')") @GetMapping("/list") public R list(Role role) { Page page = getPage(); return R.success().add("page", iRoleService.listPage(page, role)); } }
我們在list 方法上加了?@PreAuthorize(“@ss.hasPermi('system:role:list')”)?註解表示目前登入使用者擁有system:role:list 權(quán)限才能存取list 方法,否則回傳權(quán)限錯誤。
五、取得目前登入使用者權(quán)限
在 SecurityConfig 設(shè)定類別中我們定義了 UserDetailsS??erviceImpl 作為我們的使用者資訊載入的實作類,從而透過讀取資料庫中使用者的帳號、密碼與前端傳入的帳號、密碼進行比對。程式碼如下,
@Slf4j @Service @AllArgsConstructor public class UserDetailsServiceImpl implements UserDetailsService { private IUserService iUserService; private IDeptService iDeptService; private PermissionService permissionService; public static void main(String[] args) { BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); System.out.println(bCryptPasswordEncoder.encode("123456")); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 1. 讀取數(shù)據(jù)庫中當前用戶信息 User user = iUserService.getOne(new QueryWrapper().eq("user_name", username)); // 2. 判斷該用戶是否存在 if (user == null) { log.info("登錄用戶:{} 不存在.", username); throw new UsernameNotFoundException("登錄用戶:" + username + " 不存在"); } // 3. 判斷是否禁用 if (Objects.equals(UserStatusEnum.DISABLE.getCode(), user.getUserStatus())) { log.info("登錄用戶:{} 已經(jīng)被停用.", username); throw new DisabledException("登錄用戶:" + username + " 不存在"); } user.setDept(iDeptService.getById(user.getDeptId())); // 4. 獲取當前用戶的角色信息 Set rolePermission = permissionService.getRolePermission(user); // 5. 根據(jù)角色獲取權(quán)限信息 Set menuPermission = permissionService.getMenuPermission(rolePermission); return new LoginUserDetail(user, menuPermission); } }
針對 UserDetailsS??erviceImpl 的程式碼邏輯進行一個講解,大家可以配合程式碼理解。
- 讀取資料庫中目前使用者資訊
- 判斷該使用者是否存在
- 判斷是否停用
- 取得目前使用者的角色資訊
- 根據(jù)角色取得權(quán)限資訊
總結(jié)一下
本文告訴大家來說明了後管系統(tǒng)如何引入權(quán)限控制框架 Spring Security 3.0 版本以及程式碼實戰(zhàn)。相信能幫助大家對權(quán)限控制框架 Spring Security 有一個清晰的理解。後續(xù)大家可以按照本文的使用指南一步一步將 Spring Security 引入的自己的專案中用於存取權(quán)限控制。
以上是Spring Security權(quán)限控制框架使用指南的詳細內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

我有下面的程式碼:publicSecurityFilterChainsecurityFilterChain(HttpSecurityhttp)throwsException{returnhttp.httpBasic().disable().cors().and().csrf().disable().authorizeHttpRequests().requestMatchers("

Kernelsecuritycheckfailure(內(nèi)核檢查失?。┚褪且粋€比較常見的停止代碼類型,可藍屏錯誤出現(xiàn)不管是什麼原因都讓很多的有用戶們十分的苦惱,下面就讓本站來為用戶們來仔細的介紹一下17種解決方法吧。 kernel_security_check_failure藍色畫面的17種解決方法方法1:移除全部外部裝置當您使用的任何外部裝置與您的Windows版本不相容時,則可能會發(fā)生Kernelsecuritycheckfailure藍色畫面錯誤。為此,您需要在嘗試重新啟動電腦之前拔下全部外部裝置。

2023年,AI技術(shù)已成為熱門話題,對各行業(yè)產(chǎn)生了巨大影響,程式設(shè)計領(lǐng)域尤其如此。人們越來越認識到AI技術(shù)的重要性,Spring社群也不例外。隨著GenAI(GeneralArtificialIntelligence)技術(shù)的不斷進步,簡化具備AI功能的應(yīng)用程式的創(chuàng)建變得至關(guān)重要和迫切。在這個背景下,"SpringAI"應(yīng)運而生,旨在簡化開發(fā)AI功能應(yīng)用程式的過程,使其變得簡單直觀,避免不必要的複雜性。透過"SpringAI",開發(fā)者可以更輕鬆地建立具備AI功能的應(yīng)用程序,將其變得更加易於使用和操作

Spring+AI作為行業(yè)領(lǐng)導者,透過其強大、靈活的API和先進的功能,為各種行業(yè)提供了領(lǐng)先性的解決方案。在本專題中,我們將深入探討Spring+AI在各領(lǐng)域的應(yīng)用範例,每個案例都將展示Spring+AI如何滿足特定需求,實現(xiàn)目標,並將這些LESSONSLEARNED擴展到更廣泛的應(yīng)用。希望這個專題能對你有所啟發(fā),更深入地理解和利用Spring+AI的無限可能。 Spring框架在軟體開發(fā)領(lǐng)域已經(jīng)有超過20年的歷史,自SpringBoot1.0版本發(fā)布以來已有10年。現(xiàn)在,無人會質(zhì)疑,Spring

spring編程式事務(wù)的實作方式:1、使用TransactionTemplate;2、使用TransactionCallback和TransactionCallbackWithoutResult;3、使用Transactional註解;4、使用TransactionTemplate和@Transactional結(jié)合使用;5、自訂事務(wù)管理器。

Spring設(shè)定事務(wù)隔離等級的方法:1、使用@Transactional註解;2、在Spring設(shè)定檔中設(shè)定;3、使用PlatformTransactionManager;4、在Java配置類別中設(shè)定。詳細介紹:1、使用@Transactional註解,在需要進行事務(wù)管理的類別或方法上加入@Transactional註解,並在屬性中設(shè)定隔離等級;2、在Spring設(shè)定檔等等。

spring設(shè)定檔的步驟:1、建立XML設(shè)定檔;2、新增必要的依賴;3、設(shè)定資料來源;4、定義bean;5、設(shè)定其他元件;6、注入依賴;7、設(shè)定環(huán)境;8、啟用自動組裝;9、部署應(yīng)用程式;10、啟動應(yīng)用程式。詳細介紹:1、建立XML設(shè)定文件,在專案的資源目錄下建立一個XML文件,這個文件將包含Spring的設(shè)定資訊;2、加入必要的依賴等等。

在後臺管理系統(tǒng)中,通常需要存取權(quán)限控制,以限制不同使用者對介面的存取能力。如果使用者缺乏特定權(quán)限,則無法存取某些介面。本文將用waynboot-mall專案舉例,跟大家介紹常見後管系統(tǒng)如何引入權(quán)限控制框架SpringSecurity。大綱如下:waynboot-mall專案網(wǎng)址:https://github.com/wayn111/waynboot-mall一、什麼是SpringSecuritySpringSecurity是一個基於Spring框架的開源項目,旨在為Java應(yīng)用程式提供強大且靈活的安
