Spring Boot Security配置教程

1.简介

在本文中,咱们将了解Spring Boot对spring Security的支持。css

简而言之,咱们将专一于默认Security配置以及如何在须要时禁用或自定义它git

2.默认Security设置

为了增长Spring Boot应用程序的安全性,咱们须要添加安全启动器依赖项:github

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

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

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

简而言之,默认状况下,为应用程序启用身份验证。此外,内容协商用于肯定是否应使用basic或formLogin安全

有一些预约义的属性,例如:服务器

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

若是咱们不使用预约义属性spring.security.user.password配置密码并启动应用程序,咱们会注意到随机生成默认密码并在控制台日志中打印session

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

3.禁用自动配置

要放弃安全性自动配置并添加咱们本身的配置,咱们须要排除SecurityAutoConfiguration类。app

这能够经过简单的排除来完成:curl

@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启动。
这会致使问题,由于另外一个自动配置类须要咱们刚刚排除的那个,所以应用程序将没法启动

为了解决这个问题,咱们须要排除该类;而且,特定于Actuator状况,咱们须要排除ManagementWebSecurityAutoConfiguration

3.1. 禁用和超越 Security Auto-Configuration

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

经过禁用它,就像从头开始添加Spring Security依赖项和整个设置同样。这在如下几种状况下颇有用:

  • 将应用程序security与自定义security提供程序集成
  • 将已有security设置的旧Spring应用程序迁移到Spring Boot

可是,大多数状况下咱们不须要彻底禁用安全自动配置

Spring Boot的配置方式容许经过添加咱们的新/自定义配置类来超越自动配置的安全性。这一般更容易,由于咱们只是定制现有的安全设置以知足咱们的需求。

4.配置Spring Boot Security

若是咱们选择了禁用Security自动配置的路径,咱们天然须要提供本身的配置。

正如咱们以前讨论过的,这是默认的安全配置;咱们能够经过修改属性文件来自定义它。

例如,咱们能够经过添加咱们本身的密码来覆盖默认密码:

security.user.password=password

若是我们想要一个更灵活的配置,例如多个用户和角色 - 您如今须要使用完整的@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注释相当重要

若是丢失,应用程序将没法启动。只有在咱们使用WebSecurityConfigurerAdapter覆盖默认行为时,注释才是可选的。

如今,咱们应该经过几个快速实时测试验证咱们的安全配置是否正确应用:

@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依赖项来开始设置咱们的应用程序:

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

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

如今,咱们有多种选择能够继续,具体取决于咱们的应用范围。

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

若是咱们但愿咱们的应用程序是OAuth2提供程序,咱们可使用@EnableAuthorizationServer

在启动时,咱们会在日志中注意到自动配置类将为咱们的受权服务器生成客户端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

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

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

若是咱们须要将我们的应用程序做为上述类型之一,咱们只须要为应用程序属性添加一些配置

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中默认不安全的某些端点如今是安全的

这些端点包括静态资源,如/ css / ,/ js / ,/ images / ,/ webjars / ,//favicon.ico和错误端点。若是咱们须要容许对这些端点进行未经身份验证的访问,咱们能够明确地配置它**。

为了简化与安全相关的配置,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.结论

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

代码能够在Github上找

相关文章
相关标签/搜索