我是新手,正在學習 spring-boot 和 spring 安全性,在這里我正在嘗試創建一個 EmployeeManagement 應用程式,它可以對員工執行 CRUD 操作。在這個管理員應該能夠將用戶動態添加到資料庫,并且管理員應該有權訪問所有 API,而用戶應該有權查看員工只有我創建了所需的所有內容,并且我的專案在添加 spring 安全性之前運行良好,但在添加它之后,我的用戶和管理員能夠登錄但無法訪問任何 API。它顯示錯誤 403 被禁止,我無法理解為什么 spring security 沒有按照配置(http 安全)方法中提到的角色授予訪問 Urls 的權限(在這個專案中,我使用了 MySQl 資料庫、spring-boot、spring安全性和 swagger-ui)
這是我的安全配置
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/secure/**").hasRole("ADMIN").and().authorizeRequests()
.antMatchers("/", "/employees/save", "/employees/updateEmployee/{id}", "/employees/deleteEmployee/{id}")
.hasRole("ADMIN").and().authorizeRequests()
.antMatchers("/", "/employees/list", "/employees/getEmployee/{id}",
"/employees/getAllEmployeesWithTheseName/{firstname}",
"/employees/getEmployeesCustomSortedByName/{direction}")
.hasAnyRole("ADMIN", "USER")
.and()
.httpBasic().and().formLogin().loginProcessingUrl("/login")
.defaultSuccessUrl("/swagger-ui.html", true).and().cors().and().csrf().disable();
}
@Bean
public BCryptPasswordEncoder encodePWD() {
return new BCryptPasswordEncoder();
}
}
這是我得到的錯誤
{
"timestamp": "2022-11-07T15:59:26.930 00:00",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/EmployeeManagement/employees/list"
}
uj5u.com熱心網友回復:
你不能使用PathVariableinantMatchers(....)
從檔案AntPathMatcher
映射使用以下規則匹配 URL:
- ? 匹配一個字符
- * 匹配零個或多個字符
- ** 匹配路徑中的零個或多個目錄
- {spring:[az] } 匹配正則運算式 [az] 作為名為“spring”的路徑變數
所以使用:
"/employees/getEmployee/{id:[0-9] }"或者"/employees/getEmployee/*"/employees/getAllEmployeesWithTheseName/{firstname:[A-Za-z] }"或者"/employees/getAllEmployeesWithTheseName/*
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529578.html
