当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot Security配置教程

Spring Boot Security配置教程

2019年07月19日  | 移动技术网IT编程  | 我要评论

1.简介

在本文中,我们将了解spring boot对spring security的支持。

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

2.默认security设置

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

<dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-security</artifactid>
</dependency>

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

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

简而言之,默认情况下,为应用程序启用身份验证。此外,内容协商用于确定是否应使用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启动。
这会导致问题,因为另一个自动配置类需要我们刚刚排除的那个,因此应用程序将无法启动。

为了解决这个问题,我们需要排除该类;并且,特定于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提供的默认安全配置。我们了解了如何禁用或覆盖安全性自动配置机制以及如何应用新的安全性配置。

附上源码:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网