如何在SpringBoot中配置Security

本篇文章給大家分享的是有關(guān)如何在Spring Boot中配置 Security,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

在樂清等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供做網(wǎng)站、網(wǎng)站建設(shè) 網(wǎng)站設(shè)計制作按需網(wǎng)站策劃,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),高端網(wǎng)站設(shè)計,網(wǎng)絡(luò)營銷推廣,外貿(mào)網(wǎng)站制作,樂清網(wǎng)站建設(shè)費用合理。

2.默認Security設(shè)置

為了增加Spring Boot應(yīng)用程序的安全性,我們需要添加安全啟動器依賴項:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

這將包括SecurityAutoConfiguration類 - 包含初始/默認安全配置。

注意我們在這里沒有指定版本,假設(shè)項目已經(jīng)使用Boot作為父項。

簡而言之,默認情況下,為應(yīng)用程序啟用身份驗證。此外,內(nèi)容協(xié)商用于確定是否應(yīng)使用basic或formLogin。

有一些預(yù)定義的屬性,例如:

spring.security.user.name
spring.security.user.password

如果我們不使用預(yù)定義屬性spring.security.user.password配置密碼并啟動應(yīng)用程序,我們會注意到隨機生成默認密碼并在控制臺日志中打?。?/p>

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

還有一些特殊情況,這種設(shè)置還不夠。

例如,幾乎每個Spring Boot應(yīng)用程序都在類路徑中使用Actuator啟動。
這會導(dǎo)致問題,因為另一個自動配置類需要我們剛剛排除的那個,因此應(yīng)用程序?qū)o法啟動。

為了解決這個問題,我們需要排除該類;并且,特定于Actuator情況,我們需要排除

ManagementWebSecurityAutoConfiguration。

3.1. 禁用和超越 Security Auto-Configuration
禁用自動配置和超越它之間存在顯著差異。

通過禁用它,就像從頭開始添加Spring Security依賴項和整個設(shè)置一樣。這在以下幾種情況下很有用:

將應(yīng)用程序security與自定義security提供程序集成

將已有security設(shè)置的舊Spring應(yīng)用程序遷移到Spring Boot

但是,大多數(shù)情況下我們不需要完全禁用安全自動配置。

Spring Boot的配置方式允許通過添加我們的新/自定義配置類來超越自動配置的安全性。這通常更容易,因為我們只是定制現(xiàn)有的安全設(shè)置以滿足我們的需求。

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注釋至關(guān)重要。

如果丟失,應(yīng)用程序?qū)o法啟動。只有在我們使用WebSecurityConfigurerAdapter覆蓋默認行為時,注釋才是可選的。

現(xiàn)在,我們應(yīng)該通過幾個快速實時測試驗證我們的安全配置是否正確應(yīng)用:

@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 OAuth3自動配置
Spring Boot為OAuth3提供專用的自動配置支持。

在我們開始之前,讓我們添加Maven依賴項來開始設(shè)置我們的應(yīng)用程序:

<dependency>
  <groupId>org.springframework.security.oauth</groupId>
  <artifactId>spring-security-oauth3</artifactId>
</dependency>

此依賴項包括一組能夠觸發(fā)OAuth3AutoConfiguration類中定義的自動配置機制的類。

現(xiàn)在,我們有多種選擇可以繼續(xù),具體取決于我們的應(yīng)用范圍。

5.1。 OAuth3授權(quán)服務(wù)器自動配置
如果我們希望我們的應(yīng)用程序是OAuth3提供程序,我們可以使用@EnableAuthorizationServer。

在啟動時,我們會在日志中注意到自動配置類將為我們的授權(quán)服務(wù)器生成客戶端ID和客戶端密鑰,當然還有用于基本身份驗證的隨機密碼。

Using default security password: a81cb256-f243-40c0-a585-81ce1b952a98
security.oauth3.client.client-id = 39d2835b-1f87-4a77-9798-e2975f36972e
security.oauth3.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 OAuth3自動配置設(shè)置

Spring Boot OAuth3涵蓋了一些其他用例,例如:

資源服務(wù)器 - @EnableResourceServer

客戶端應(yīng)用程序 - @ EnableOAuth3Sso或@ EnableOAuth3Client

如果我們需要將我們的應(yīng)用程序作為上述類型之一,我們只需要為應(yīng)用程序?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)身份驗證的訪問,我們可以明確地配置它**。

為了簡化與安全相關(guān)的配置,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

springboot是什么

springboot一種全新的編程規(guī)范,其設(shè)計目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程,SpringBoot也是一個服務(wù)于框架的框架,服務(wù)范圍是簡化配置文件。

以上就是如何在Spring Boot中配置 Security,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

文章名稱:如何在SpringBoot中配置Security
文章路徑:http://muchs.cn/article40/phosho.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號、動態(tài)網(wǎng)站、自適應(yīng)網(wǎng)站定制網(wǎng)站、虛擬主機、電子商務(wù)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站