搜尋
首頁電腦教學電腦知識Spring Security權限控制框架使用指南

Spring Security權限控制框架使用指南

Feb 18, 2024 pm 05:00 PM
springsecurityspring securityspring mvcwaynboot

Spring Security权限控制框架使用指南

在背景管理系統中,通常需要存取權限控制,以限制不同使用者對介面的存取能力。如果使用者缺乏特定權限,則無法存取某些介面。

本文將用 waynboot-mall 專案舉例,為大家介紹常見後管系統如何引入權限控制框架 Spring Security。大綱如下:

waynboot-mall 專案網址:https://github.com/wayn111/waynboot-mall

一、什麼是 Spring Security

Spring Security 是一個基於 Spring 框架的開源項目,旨在為 Java 應用程式提供強大且靈活的安全解決方案。 Spring Security 提供了以下特性:

  • 認證:支援多種認證機制,如表單登入、HTTP 基本認證、OAuth2、OpenID 等。
  • 授權:支援基於角色或權限的存取控制,以及基於表達式的細粒度控制。
  • 防護:提供了多種防護措施,例如防止會話固定、點擊劫持、跨站請求偽造等攻擊。
  • 整合:與 Spring 框架和其他第三方程式庫和框架進行無縫集成,如 Spring MVC、Thymeleaf、Hibernate 等。

二、如何引進 Spring Security

在 waynboot-mall 專案中直接引入 spring-boot-starter-security 依賴,


org.springframework.boot
spring-boot-starter-security
3.1.0

三、如何設定 Spring Security

在 Spring Security 3.0 中要設定 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()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated();
})
.headers(httpSecurityHeadersConfigurer -> {
httpSecurityHeadersConfigurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable);
});
// 处理跨域请求中的Preflight请求(cors),设置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();
}
/**
 * 强散列哈希加密实现
 */
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}

這裡詳細介紹下 SecurityConfig 設定類別:

  • filterChain(HttpSecurity httpSecurity) 方法是存取控制的核​​心方法,這裡面可以針對 url 設定是否需要權限認證、cors 設定、csrf 設定、使用者資訊載入設定、jwt 過濾器攔截設定等眾多功能。
  • authenticationManager(AuthenticationConfiguration authenticationConfiguration) 方法適用於啟用認證接口,需要手動聲明,否則啟動報錯。
  • bCryptPasswordEncoder() 方法使用者定義使用者登入時的密碼加密策略,需要手動聲明,否則啟動報錯。

四、如何使用 Spring Security

要使用 Spring Security,只需要在需要控制存取權的方法或類別上新增對應的 @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 權限才能存取list 方法,否則回傳權限錯誤。

五、取得目前登入使用者權限

在 SecurityConfig 設定類別中我們定義了 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. 读取数据库中当前用户信息
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("登录用户:{} 已经被停用.", username);
throw new DisabledException("登录用户:" + username + " 不存在");
}
user.setDept(iDeptService.getById(user.getDeptId()));
// 4. 获取当前用户的角色信息
Set rolePermission = permissionService.getRolePermission(user);
// 5. 根据角色获取权限信息
Set menuPermission = permissionService.getMenuPermission(rolePermission);
return new LoginUserDetail(user, menuPermission);
}
}

針對 UserDetailsS​​erviceImpl 的程式碼邏輯進行一個講解,大家可以配合程式碼理解。

  • 讀取資料庫中目前使用者資訊
  • 判斷該使用者是否存在
  • 判斷是否停用
  • 取得目前使用者的角色資訊
  • 根據角色取得權限資訊

總結一下

本文告訴大家來說明了後管系統如何引入權限控制框架 Spring Security 3.0 版本以及程式碼實戰。相信能幫助大家對權限控制框架 Spring Security 有一個清晰的理解。後續大家可以按照本文的使用指南一步一步將 Spring Security 引入的自己的專案中用於存取權限控制。

以上是Spring Security權限控制框架使用指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:每日运维。如有侵權,請聯絡admin@php.cn刪除
Zlib1.dll缺少或找不到錯誤?用簡單的動作修復 -  MinitoolZlib1.dll缺少或找不到錯誤?用簡單的動作修復 - MinitoolApr 16, 2025 am 12:52 AM

什麼是zlib1.dll?有些人遇到“ zlib1.dll丟失”錯誤或zlib1.dll試圖打開包含zlib1.dll的應用程序時找不到錯誤。為了解決這些相關錯誤,PHP.CN網站上的這篇文章可以為您提供一些我

Autofill在Excel中不起作用嗎?這是修復程序! -  MinitoolAutofill在Excel中不起作用嗎?這是修復程序! - MinitoolApr 16, 2025 am 12:51 AM

你們中有些人可能會發現自動填充沒有在Excel中工作。您能提出任何解決方案嗎?如果沒有,那麼您就會到達正確的位置。 PHP.CN網站上的這篇文章將為您提供6種方法來解決Excel Autofill無法正常工作的方法。

Windows 7 Starter Edition:這是什麼?如何下載? -  MinitoolWindows 7 Starter Edition:這是什麼?如何下載? - MinitoolApr 16, 2025 am 12:50 AM

什麼是Windows 7 Starter版本? Windows 7 Starter版的局限性是什麼?如何獲得Windows 7首發版ISO?來自PHP.CN的這篇文章為您提供了有關Windows 7 Starter Edition的詳細信息。

使用此頂部指南在Windows中以其他用戶的方式運行應用程序使用此頂部指南在Windows中以其他用戶的方式運行應用程序Apr 16, 2025 am 12:49 AM

運行應用程序時,您是否通過登錄目前然後登錄另一個應用程序來更改帳戶感到困擾? PHP.CN收集了一些有效的方法來幫助您在Windows 10和Windows 11中作為其他用戶運行應用程序。

修復:Dropbox下載您的文件有錯誤修復:Dropbox下載您的文件有錯誤Apr 16, 2025 am 12:48 AM

您是否患有“ Dropbox下載文件的錯誤下載您的文件”錯誤?現在閱讀PHP.CN發表的這篇文章,以獲取有關此問題的一些有用解決方案。

修復所選文件的5種方法未在文件資源管理器中突出顯示-Minitool修復所選文件的5種方法未在文件資源管理器中突出顯示-MinitoolApr 16, 2025 am 12:47 AM

您是否對“所選文件在文件資源管理器中未突出顯示”的問題感到困擾?您知道如何解決嗎?如果沒有,您可以在PHP.CN上閱讀此帖子,以獲取幾個可行解決方案,以使所選文件在文件資源管理器中可見。

修復任務欄中缺少語言欄 - 經過驗證的指南修復任務欄中缺少語言欄 - 經過驗證的指南Apr 16, 2025 am 12:46 AM

如果您使用多語言,語言欄是必不可少的。您可以通過從任務欄調整設置來更改輸入語言。但是,當您打開計算機時,語言條可能有一天會消失。如何修復語言欄丟失

如何將外部驅動器連接到Android手機或平板電腦? -  Minitool如何將外部驅動器連接到Android手機或平板電腦? - MinitoolApr 16, 2025 am 12:45 AM

是否想使用外部驅動器來擴展手機的存儲空間?可以這樣做。此php.cn帖子向您展示瞭如何將外部驅動器連接到手機的指南。此外,如果您需要從外部驅動器中恢復數據,則可以嘗試PHP

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器