# Spring Boot Security ###### tags: `Spring Framework`、`Spring Boot Security` ## 設定 Spring Security > Ex: CSRF、路徑權限、驗證方法及自訂登入登出頁面等。 使用 `HttpSecurity` 物件進行安全性設定,**以下方法皆位於此物件內**。 *P.S. 使用 `and()` 可以再次取得 `HttpSecurity` 物件。* - 針對路徑關閉 CSRF ```kotlin csrf().ignoringAntMatchers("/**") ``` - 關閉 CSRF ```kotlin csrf().disable() ``` - 針對路徑設定請求權限規則 ```kotlin authorizeRequests() .antMatchers("/") // 設定要套用權限的路徑 .permitAll() // 設定對應的動作 ``` #### 常用對應動作: `permitAll()`:允許所有使用者請求。 `hasAnyRole(vararg roles:String!)`:允許符合其中之一權限的使用者請求。 `authenticated()`:允許任何有通過驗證的使用者的請求。 *P.S. 權限規則判斷優先權是由上到下,故允許所有請求的路徑建議放在最後面設定* #### 範例設定 ```kotlin authorizeRequests() .antMatchers("/user") .authenticated() .antMatchers("/**") .permitAll() ``` - 使用 Oauth2 登入 ([Preuseing guide](/W9UOk9v4SP2M0OSHJ_unMA)) ```kotlin oauth2Login() ``` - 使用表單登入 ```kotlin formLogin() ``` ### 範例設定 ```kotlin override fun configure(http: HttpSecurity) { http.csrf().disable() // 關閉 CSRF http.authorizeRequests() // 驗證請求 .antMatchers("/user") // 要套用權限設定的路徑 .authenticated() // 僅限已驗證的請求進入 .antMatchers("/**") // 用 "/**" 表示根目錄以下的所有路徑 .permitAll() // 允許所有請求 .and() .formLogin() // 啟用表單登入 .and() .oauth2Login() // 啟用 OAuth2 登入 } ```