Spring Boot安全自动配置

1.简介

在本文中,我们将了解Spring Boot对安全性的看法。

简而言之,我们将专注于默认安全配置以及如何在需要时禁用或自定义它。

2.默认安全设置

为了增加Spring Boot应用程序的安全性,我们需要添加安全启动器依赖项

1

2

3

4

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-security</artifactId>

</dependency>

这将包括SecurityAutoConfiguration类 - 包含初始/默认安全配置。

注意我们在这里没有指定版本,假设项目已经使用Boot作为父项。

简单地说,默认情况下,应用程序将启用基本身份验证。有一些预定义的属性,例如:

1

2

security.user.name=user

security.basic.enabled=true

如果我们启动应用程序,我们会注意到默认密码是随机生成的并打印在控制台日志中:

1

Using default security password: c8be15de-4488-4490-9dc6-fab3f91435c6

有关更多默认值,请参阅安全属性一章中的Spring Boot公共应用程序属性

3.禁用自动配置

要丢弃安全性自动配置并添加我们自己的配置,我们需要排除SecurityAutoConfiguration类。

这可以通过简单的排除来完成:

1

2

3

4

5

6

7

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })

public class SpringBootSecurityApplication {

 

    public static void main(String[] args) {

        SpringApplication.run(SpringBootSecurityApplication.class, args);

    }

}

或者通过在application.properties文件中添加一些配置:

1

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration

还有一些特殊情况,这种设置还不够。

例如,几乎每个Spring Boot应用程序都在类路径中使用Actuator启动。这会导致问题,因为另一个自动配置类需要我们刚刚排除的那个,因此应用程序将无法启动。

为了解决这个问题,我们需要排除该类; 并且,特定于执行器情况,我们需要排除ManagementWebSecurityAutoConfiguration

3.1。禁用与超越安全自动配置

禁用自动配置和超越它之间存在显着差异。

通过禁用它,就像从头开始添加Spring Security依赖项和整个设置一样。在以下几种情况下,这可能很有用:

  1. 将应用程序安全性与自定义安全提供程序集成
  2. 将已有安全设置的旧Spring应用程序迁移到Spring Boot

但是,大多数情况下我们不需要完全禁用安全自动配置。

Spring Boot的配置方式允许通过添加新的/自定义配置类来超越自动配置的安全性。这通常更容易,因为我们只是定制现有的安全设置来满足我们的需求。

4.配置Spring Boot Security

如果我们选择了禁用安全自动配置的路径,我们自然需要提供自己的配置。

正如我们之前讨论的那样,这是默认的安全配置; 我们可以通过修改属性文件来自定义它。

例如,我们可以通过添加我们自己的密码来覆盖默认密码:

1

security.user.password=password

如果我们想要一个更灵活的配置,例如多个用户和角色 - 您现在需要使用完整的@Configuration类:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

@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注释是至关重要的,如果我们禁用默认的安全配置。

如果丢失,应用程序将无法启动。如果我们只是使用WebSecurityConfigurerAdapter覆盖默认行为,则注释只是可选的。

现在,我们应该通过几个快速实时测试验证我们的安全配置是否正确应用:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

@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,所以任何可以用这个完成的安全配置,或者它支持的任何集成,都可以在Spring Boot中实现。

5. Spring Boot OAuth2自动配置

Spring Boot为OAuth2提供专用的自动配置支持。

在我们开始之前,让我们添加Maven依赖项来开始设置我们的应用程序:

1

2

3

4

<dependency>

   <groupId>org.springframework.security.oauth</groupId>

   <artifactId>spring-security-oauth2</artifactId>

</dependency>

此依赖项包括一组能够触发OAuth2AutoConfiguration类中定义的自动配置机制的类。

现在,我们有多种选择可以继续,具体取决于我们的应用范围。

5.1。OAuth2授权服务器自动配置

如果我们希望我们的应用程序是OAuth2提供程序,我们可以使用@EnableAuthorizationServer

在启动时,我们会在日志中注意到自动配置类将为我们的授权服务器生成客户端ID和客户端密钥,当然还有用于基本身份验证的随机密码。

1

2

3

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

这些凭据可用于获取访问令牌:

1

2

3

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涵盖了一些其他用例,例如:

  1. 资源服务器 - @EnableResourceServer
  2. 客户端应用程序 - @ EnableOAuth2Sso@ EnableOAuth2Client

如果我们需要将我们的应用程序作为上述类型之一,我们只需要为应用程序属性添加一些配置。

可以在Spring Boot Common Application Properties中找到所有OAuth2特定属性

六,结论

在本文中,我们重点介绍Spring Boot提供的默认安全配置。我们了解了如何禁用或覆盖安全性自动配置机制以及如何应用新的安全性配置。

源代码可以在Github上找到。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值