Spring Boot Security配置教程
1.簡介
在本文中,我們將了解Spring Boot對spring Security的支持。
簡而言之,我們將專注于默認Security配置以及如何在需要時禁用或自定義它。
2.默認Security設置
為了增加Spring Boot應用程序的安全性,我們需要添加安全啟動器依賴項:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
這將包括SecurityAutoConfiguration類 - 包含初始/默認安全配置。
注意我們在這里沒有指定版本,假設項目已經(jīng)使用Boot作為父項。
簡而言之,默認情況下,為應用程序啟用身份驗證。此外,內(nèi)容協(xié)商用于確定是否應使用basic或formLogin。
有一些預定義的屬性,例如:
spring.security.user.name spring.security.user.password
如果我們不使用預定義屬性spring.security.user.password配置密碼并啟動應用程序,我們會注意到隨機生成默認密碼并在控制臺日志中打印:
Using default security password: c8be15de-4488-4490-9dc6-fab3f91435c6
3.禁用自動配置
要放棄安全性自動配置并添加我們自己的配置,我們需要排除SecurityAutoConfiguration類。
這可以通過簡單的排除來完成:
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class SpringBootSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSecurityApplication.class, args);
}
}
或者通過在application.properties文件中添加一些配置:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
還有一些特殊情況,這種設置還不夠。
例如,幾乎每個Spring Boot應用程序都在類路徑中使用Actuator啟動。
這會導致問題,因為另一個自動配置類需要我們剛剛排除的那個,因此應用程序?qū)o法啟動。
為了解決這個問題,我們需要排除該類;并且,特定于Actuator情況,我們需要排除
ManagementWebSecurityAutoConfiguration。
3.1. 禁用和超越 Security Auto-Configuration
禁用自動配置和超越它之間存在顯著差異。
通過禁用它,就像從頭開始添加Spring Security依賴項和整個設置一樣。這在以下幾種情況下很有用:
將應用程序security與自定義security提供程序集成
將已有security設置的舊Spring應用程序遷移到Spring Boot
但是,大多數(shù)情況下我們不需要完全禁用安全自動配置。
Spring Boot的配置方式允許通過添加我們的新/自定義配置類來超越自動配置的安全性。這通常更容易,因為我們只是定制現(xiàn)有的安全設置以滿足我們的需求。
4.配置Spring Boot Security
如果我們選擇了禁用Security自動配置的路徑,我們自然需要提供自己的配置。
正如我們之前討論過的,這是默認的安全配置;我們可以通過修改屬性文件來自定義它。
例如,我們可以通過添加我們自己的密碼來覆蓋默認密碼:
security.user.password=password
如果我們想要一個更靈活的配置,例如多個用戶和角色 - 您現(xiàn)在需要使用完整的@Configuration類:
@Configuration
@EnableWebSecurity
public class BasicConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("USER")
.and()
.withUser("admin")
.password("admin")
.roles("USER", "ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
如果我們禁用默認安全配置,則@EnableWebSecurity注釋至關重要。
如果丟失,應用程序?qū)o法啟動。只有在我們使用WebSecurityConfigurerAdapter覆蓋默認行為時,注釋才是可選的。
現(xiàn)在,我們應該通過幾個快速實時測試驗證我們的安全配置是否正確應用:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class BasicConfigurationIntegrationTest {
TestRestTemplate restTemplate;
URL base;
@LocalServerPort int port;
@Before
public void setUp() throws MalformedURLException {
restTemplate = new TestRestTemplate("user", "password");
base = new URL("http://localhost:" + port);
}
@Test
public void whenLoggedUserRequestsHomePage_ThenSuccess()
throws IllegalStateException, IOException {
ResponseEntity<String> response
= restTemplate.getForEntity(base.toString(), String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(response
.getBody()
.contains("Baeldung"));
}
@Test
public void whenUserWithWrongCredentials_thenUnauthorizedPage()
throws Exception {
restTemplate = new TestRestTemplate("user", "wrongpassword");
ResponseEntity<String> response
= restTemplate.getForEntity(base.toString(), String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
assertTrue(response
.getBody()
.contains("Unauthorized"));
}
}
實際上,Spring Boot Security的背后是Spring Security,所以任何可以用這個完成的安全配置,或者這個支持的任何集成都可以實現(xiàn)到Spring Boot中。
5. Spring Boot OAuth2自動配置
Spring Boot為OAuth2提供專用的自動配置支持。
在我們開始之前,讓我們添加Maven依賴項來開始設置我們的應用程序:
<dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency>
此依賴項包括一組能夠觸發(fā)OAuth2AutoConfiguration類中定義的自動配置機制的類。
現(xiàn)在,我們有多種選擇可以繼續(xù),具體取決于我們的應用范圍。
5.1。 OAuth2授權(quán)服務器自動配置
如果我們希望我們的應用程序是OAuth2提供程序,我們可以使用@EnableAuthorizationServer。
在啟動時,我們會在日志中注意到自動配置類將為我們的授權(quán)服務器生成客戶端ID和客戶端密鑰,當然還有用于基本身份驗證的隨機密碼。
Using default security password: a81cb256-f243-40c0-a585-81ce1b952a98 security.oauth2.client.client-id = 39d2835b-1f87-4a77-9798-e2975f36972e security.oauth2.client.client-secret = f1463f8b-0791-46fe-9269-521b86c55b71
這些憑據(jù)可用于獲取訪問令牌:
curl -X POST -u 39d2835b-1f87-4a77-9798-e2975f36972e:f1463f8b-0791-46fe-9269-521b86c55b71 \ -d grant_type=client_credentials -d username=user -d password=a81cb256-f243-40c0-a585-81ce1b952a98 \ -d scope=write http://localhost:8080/oauth/token
5.2。其他Spring Boot OAuth2自動配置設置
Spring Boot OAuth2涵蓋了一些其他用例,例如:
資源服務器 - @EnableResourceServer
客戶端應用程序 - @ EnableOAuth2Sso或@ EnableOAuth2Client
如果我們需要將我們的應用程序作為上述類型之一,我們只需要為應用程序?qū)傩蕴砑右恍┡渲谩?/p>
6. Spring Boot 2 security與Spring Boot 1 security
與Spring Boot 1相比,Spring Boot 2大大簡化了自動配置。
在Spring Boot 2中,如果我們想要自己的安全配置,我們可以簡單地添加一個自定義的WebSecurityConfigurerAdapter。這將禁用默認自動配置并啟用我們的自定義安全配置。
Spring Boot 2使用Spring Security的大部分默認值。因此,默認情況下,Spring Boot 1中默認不安全的某些端點現(xiàn)在是安全的。
這些端點包括靜態(tài)資源,如/ css / ,/ js / ,/ images / ,/ webjars / ,//favicon.ico和錯誤端點。如果我們需要允許對這些端點進行未經(jīng)身份驗證的訪問,我們可以明確地配置它**。
為了簡化與安全相關的配置,Spring Boot 2刪除了以下Spring Boot 1屬性:
security.basic.authorize-mode security.basic.enabled security.basic.path security.basic.realm security.enable-csrf security.headers.cache security.headers.content-security-policy security.headers.content-security-policy-mode security.headers.content-type security.headers.frame security.headers.hsts security.headers.xss security.ignored security.require-ssl security.sessions
7.結(jié)論
在本文中,我們重點介紹Spring Boot提供的默認安全配置。我們了解了如何禁用或覆蓋安全性自動配置機制以及如何應用新的安全性配置。
附上源碼:https://github.com/eugenp/tutorials/tree/master/spring-boot-security
相關文章
Java高并發(fā)BlockingQueue重要的實現(xiàn)類詳解
這篇文章主要給大家介紹了關于Java高并發(fā)BlockingQueue重要的實現(xiàn)類的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01
SpringCloud服務接口調(diào)用OpenFeign及使用詳解
這篇文章主要介紹了SpringCloud服務接口調(diào)用——OpenFeign,在學習Ribbon時,服務間調(diào)用使用的是RestTemplate+Ribbon實現(xiàn),而Feign在此基礎上繼續(xù)進行了封裝,使服務間調(diào)用變得更加方便,需要的朋友可以參考下2023-04-04
Java子線程無法獲取Attributes的解決方法(最新推薦)
在Java多線程編程中,子線程無法直接獲取主線程設置的Attributes是一個常見問題,本文探討了這一問題的原因,并提供了兩種解決方案,對Java子線程無法獲取Attributes的解決方案感興趣的朋友一起看看吧2025-01-01
Java報錯net.dean.jraw.http.NetworkException異常的原因及解決方法
在開發(fā)涉及網(wǎng)絡通信的Java應用程序時,我們經(jīng)常需要處理各種網(wǎng)絡異常,net.dean.jraw.http.NetworkException是在使用jRAW庫時可能遇到的一個異常,本文將詳細探討NetworkException的成因,并提供多種解決方案,需要的朋友可以參考下2024-12-12
SpringBoot中Druid連接池與多數(shù)據(jù)源切換的方法
微服務架構(gòu)中多數(shù)據(jù)源切換是個常見的需求,Spring Boot 提供了強大的支持來簡化這一過程.本文給大家介紹了SpringBoot中Druid連接池與多數(shù)據(jù)源切換的方法,需要的朋友可以參考下2024-11-11
如何解決shardingsphere報錯Missing?the?data?source?name:‘null‘
使用ShardingSphere進行分庫操作時,如果遇到“Missing?the?datasource?name:?‘null’”的錯誤,通常是因為所操作的表沒有配置相關的路由信息,例如,如果在properties中僅配置了health_record和health_task的路由規(guī)則2024-11-11

