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提供的默认安全配置。我们了解了如何禁用或覆盖安全性自动配置机制以及如何应用新的安全性配置。

代码可以在Github上找

Spring Boot Security配置教程的更多相关文章

  1. Spring Boot Security 使用教程

    虽然,我在实际项目中使用的是 shiro 进行权限管理,但 spring boot security 早已大名鼎鼎,虽然他的入门要相对复杂一点,但是设计视乎更加吸引人. 本章节就是以一篇快速入门 sp ...

  2. 转:spring boot log4j2配置(使用log4j2.yml文件)---YAML 语言教程

    转:spring boot log4j2配置(使用log4j2.yml文件) - CSDN博客http://blog.csdn.net/ClementAD/article/details/514988 ...

  3. Spring Boot Security 整合 JWT 实现 无状态的分布式API接口

    简介 JSON Web Token(缩写 JWT)是目前最流行的跨域认证解决方案.JSON Web Token 入门教程 - 阮一峰,这篇文章可以帮你了解JWT的概念.本文重点讲解Spring Boo ...

  4. spring boot 环境配置(profile)切换

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  5. 玩转spring boot——properties配置

    前言 在以往的java开发中,程序员最怕大量的配置,是因为配置一多就不好统一管理,经常出现找不到配置的情况.而项目中,从开发测试环境到生产环境,往往需要切换不同的配置,如测试数据库连接换成生产数据库连 ...

  6. Spring Boot Security OAuth2 实现支持JWT令牌的授权服务器

    概要 之前的两篇文章,讲述了Spring Security 结合 OAuth2 .JWT 的使用,这一节要求对 OAuth2.JWT 有了解,若不清楚,先移步到下面两篇提前了解下. Spring Bo ...

  7. Spring Boot Security 整合 OAuth2 设计安全API接口服务

    简介 OAuth是一个关于授权(authorization)的开放网络标准,在全世界得到广泛应用,目前的版本是2.0版.本文重点讲解Spring Boot项目对OAuth2进行的实现,如果你对OAut ...

  8. Spring Boot自动配置原理、实战

    Spring Boot自动配置原理 Spring Boot的自动配置注解是@EnableAutoConfiguration, 从上面的@Import的类可以找到下面自动加载自动配置的映射. org.s ...

  9. Spring Boot 揭秘与实战 附录 - Spring Boot 公共配置

    Spring Boot 公共配置,配置 application.properties/application.yml 文件中. 摘自:http://docs.spring.io/spring-boot ...

随机推荐

  1. 网络编程学习笔记-listen函数

    listen函数使用主动连接套接口变为被连接套接口,使得一个进程可以接受其它进程的请求,从而成为一个服务器进程.在TCP服务器编程中listen函数把进程变为一个服务器,并指定相应的套接字变为被动连接 ...

  2. linux ssh 命令使用解析

    前一阵远程维护Linux服务器,使用的是SSH,传说中的secure shell. 登陆:ssh [hostname] -u user 输入密码:***** 登 陆以后就可以像控制自己的机器一样控制它 ...

  3. android自定义控件(二) 入门,继承View

    转载请注明地址:http://blog.csdn.net/ethan_xue/article/details/7313788 ps: 可根据apidemo里LableView,list4,list6学 ...

  4. POJ3728The merchant (倍增)(LCA)(DP)(经典)(||并查集压缩路径?)

    There are N cities in a country, and there is one and only one simple path between each pair of citi ...

  5. bzoj 4515: 游戏 树链剖分+线段树

    题目大意: http://www.lydsy.com/JudgeOnline/problem.php?id=4515 题解: 先让我%一发lych大佬点我去看dalao的题解 讲的很详细. 这里纠正一 ...

  6. Jmeter提取响应数据的结果保存到本地的一个文件

    原文地址: https://www.cnblogs.com/whitewasher/p/9504728.html 当做性能压测时,可能会需要把响应数据的一些字段统计出来.这里简单介绍一下. 1.首先把 ...

  7. [poj1741]Tree(点分治+容斥原理)

    题意:求树中点对距离<=k的无序点对个数. 解题关键:树上点分治,这个分治并没有传统分治的合并过程,只是分成各个小问题,并将各个小问题的答案相加即可,也就是每层的复杂度并不在合并的过程,是在每层 ...

  8. 《Java多线程编程核心技术》读后感(十六)

    线程组 线程组的作用是,可以批量的管理线程或线程组对象,有效地对线程或线程组对象进行组织 线程对象关联线程组:1级关联 package Seven; public class ThreadA exte ...

  9. c# sleep 例子-线程挂起

    using System; using System.Threading; public class arr { public static void Main() { //int[] arr; // ...

  10. 2018年第九届蓝桥杯国赛试题(JavaA组)

    1.结果填空 (满分13分)2.结果填空 (满分39分)3.代码填空 (满分27分)4.程序设计(满分45分)5.程序设计(满分71分)6.程序设计(满分105分) 1.标题:三角形面积 已知三角形三 ...