我正在努力理解 Spring Security/Spring Boot 在幕后到底做了什么,以及如何實作基于表單的身份驗證并運行(https://docs.spring.io/spring-security/reference /servlet/authentication/passwords/form.html)。
作為參考,我正在構建一個 web 應用程式,目前正在開發使用 Spring Boot 開發的后端。資料存盤在非關系資料庫中。我還沒有構建前端,我使用 Postman 來測驗我的 API。
我按照這個(https://www.youtube.com/watch?v=her_7pa0vrg)和本教程(https://www.marcobehler.com/guides/spring-security)來了解如何使用 Spring Security ,鑒于官方檔案的龐大規模和分散性(https://docs.spring.io/spring-security/reference/features/index.html)。兩個教程都使用了一個已棄用的類,但我選擇暫時使用它以更輕松地構建功能性應用程式 - 稍后會更改它。
我設法理解的是,Spring Security 使用一系列方法(包含在一系列 Filter 類中)過濾客戶端請求,而我們所做的基本上是宣告這些過濾器應該如何操作,而不是自己撰寫代碼。此宣告是通過 Java 配置類完成的,該類確定哪些資源是公開可用的,哪些資源隱藏在身份驗證墻后面,哪些資源除了經過身份驗證之外還需要特定權限才能訪問。此外,此組態檔也是我們宣告允許的身份驗證方法的地方(基于表單的身份驗證屬于此類)。
以下是我的(為便于理解而編輯)組態檔:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final PasswordEncoder passwordEncoder;
private final AppUserDetailsService appUserService;
@Autowired
public SecurityConfiguration(PasswordEncoder passwordEncoder, AppUserDetailsService appUserService){
this.passwordEncoder = passwordEncoder;
this.appUserService = appUserService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
// ... other configuration to protect resources
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/login")
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder);
provider.setUserDetailsService(appUserService);
return provider;
}
}
其中 passwordEncoder 和 appUserService 是兩個組件,在各自的類中宣告,分別用于對用戶密碼進行編碼和獲取用戶認證細節(在實作 UserDetails 介面的類中,見https://docs.spring. io/spring-security/site/docs/current/api/org/springframework/security/core/userdetails/UserDetails.html和)來自資料庫。
現在,根據我對官方檔案(https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/form.html)的理解,我在配置類中構建的 DaoAuthenticationProvider 應該注意的認證事項。除了上面提到的之外,我不需要在我的代碼中定義任何其他內容。那是對的嗎?這在今天似乎不起作用,但我的郵遞員請求可能有問題 - 提前謝謝你!
編輯(參考我在@Toerktumlare 的回答下的第二批評論):
我的組態檔現在看起來像這樣(省略了 UserDetailsS??ervice 和 PasswordEncrypter):
@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.anyRequest().authenticated()
.antMatchers("/").permitAll()
.antMatchers("/register/**").permitAll()
.antMatchers("someUrl/{username}").access("@userSecurity.isSameUser(authentication, #username)")
.antMatchers("/someOtherUrl/{username}/**").access("@userSecurity.isSameUser(authentication, #username)")
)
.formLogin((formLogin) ->
formLogin.loginPage("/login")
.permitAll()
)
.logout((logout) ->
logout.deleteCookies("remove")
.invalidateHttpSession(false)
.logoutSuccessUrl("/login")
);
return http.build();
}
}
我得到這個編譯錯誤:“AuthorizeHttpRequestsConfigurer.AuthorizedUrl 型別中的方法訪問(AuthorizationManager)不適用于引數(字串)”,我得到了。我沒有得到的是官方檔案似乎確實使用了這個帶有字串引數的 .access() 方法(https://docs.spring.io/spring-security/reference/servlet/authorization/expression-based.access() )。 html#el-access-web-beans)。我猜他們正在使用不同的 .access() 方法,但我不知道如何。
uj5u.com熱心網友回復:
您與大多數從 spring 安全性開始的人一樣犯了同樣的錯誤。
您沒有閱讀 spring 安全檔案的架構章節和身份驗證架構章節,而是使用谷歌搜索并遵循過時的教程。
您鏈接到https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/form.html,它清楚地顯示沒有使用,DaoAuthenticationProvider但您仍然實作了一個。
因此,讓我們查看您的代碼:
WebSecurityConfigurerAdapter已棄用,不應使用,因此請將其洗掉。您現在需要做的就是構建一個安全配置并將其作為 bean 回傳到背景關系中。
然后你添加了兩者FormLogin,httpBasic這是兩種完全不同的身份驗證方式。我希望你能意識到這一點。
基本記錄在這里。此處記錄了表單登錄。
最后,如果您提供 aUserDetailsService和 aPasswordEncoder但無需配置您自己的AuthenticationProvider. DaoAuthenticationProvider只要您將它們作為@Beans 提供給背景關系,Spring 安全性就會自行理解您想要 a并為您構建它。
因此,您可以洗掉大部分其余代碼。
所以這就是你的最終代碼的樣子:
@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.anyRequest().authenticated()
)
.formLogin((formLogin) ->
formLogin.loginPage("/login")
.permittAll();
)
.logout((logout) ->
logout.deleteCookies("remove")
.invalidateHttpSession(false)
.logoutSuccessUrl("/login")
);
return http.build();
}
@Bean
public CustomUserDetailsService customUserDetailsService() {
return new AppUserDetailsService();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new SCryptPasswordEncoder();
}
}
你真的不需要更多。
uj5u.com熱心網友回復:
我終于設法讓整個作業正常進行。請注意,我還沒有對此進行過廣泛的測驗,所以一旦我這樣做了,我會回到這個問題上,并在必要時更新這個答案。
至于我的問題的第一部分(最初是整個問題:“我需要自己實作什么?”),我自己需要實作的唯一東西是 UserDetailsS??ervice 和 PasswordEncoder 介面。前者是負責檢索用戶詳細資訊的類(顯然,對資料庫的實際訪問可以委托給另一個類,如使用 Spring Data 的 Spring Repository 的)。Spring Security 確實提供了一種實作,以防萬一有記憶體資料庫或關系資料庫,但這不是我的情況。用戶必須撰寫自己的實作絕對是有道理的,因為 Spring 不會強制以任何特定方式存盤用戶憑據,因此無法自動知道在哪里檢索所述憑據。
我還實作了一個 SecurityFilterChain bean(就像@Toerktumlare 在他的回答中所做的那樣)。在構建自己的應用程式時,您很可能也需要這樣做,但即使沒有宣告 SecurityFilterChain bean*,您也可能會獲得基于表單的身份驗證。我沒有對此進行測驗,但肯定在檔案中的某個地方提到了它(如果我找到它并且有時間,稍后會鏈接它)。
一旦您的自定義 UserDetailsS??ervice 和 PasswordEncoder 實作被撰寫并配置為 bean 并因此可供 Spring 自行實體化,您就完成了。Spring 會自動將它們添加到它的 AuthenticationProvider 中(不需要實作這個!)并使用它們進行身份驗證。
現在,進入我的問題的第二部分(“切換到 http.authorizeHttpRequests() 后如何讓.access()方法作業?”),我最終不得不切換到實作請求的功能介面.access 方法在這個新設定中。它現在按預期作業。我仍然對 Spring 檔案中的片段感到困惑,他們在其中使用帶有 String 引數的方法(注意:鏈接會將您重定向到該部分,我說的是該部分中的第二個片段(標題為“示例1.參考方法“)。):要么我遺漏了某些東西,要么是他們的錯誤。如果我有時間,也會進一步調查。
*NB:從技術上講,我認為即使您沒有定義自己的 UserServiceDetails 實作,基于表單的身份驗證也可以作業:Spring 將使用它自己的實作之一并為您生成用戶和密碼。它還會列印一條訊息,說明在生產環境中您需要使用自己的 UserDetailsS??ervice,所以我只是為了完整起見而提及這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/515169.html
標籤:弹簧靴弹簧MVC弹簧安全
