第2章 Spring Security 的环境设置与基础配置(2024 最新版)(上)

简介: 第2章 Spring Security 的环境设置与基础配置(2024 最新版)

9526b1d6ced59dd11678343f8411959.png

2.1 安装和配置 Spring Boot

2.1.1 基础知识详解

在深入 Spring Boot 的世界之前,让我们先了解一些基础知识,这就像是在开始一场激动人心的旅行前查看地图一样。

Spring Boot 的核心概念

  1. 自动配置: Spring Boot 的自动配置机制旨在根据添加的依赖自动配置你的应用程序。这就像有一个智能助手,根据你的需求自动为你准备一切。
  2. 起步依赖(Starters): 这些特殊的依赖项是预设的模板,它们为你提供了一切必需的依赖组合,帮助你快速启动一个特定类型的项目。比如,spring-boot-starter-web 就包含了构建 web 应用所需的所有基础设施。
  3. 内嵌服务器: Spring Boot 应用通常会内嵌一个 Tomcat、Jetty 或 Undertow 服务器,这意味着你不需要单独安装一个服务器就可以运行你的应用。
  4. 无代码生成和 XML 配置: 与传统的 Spring 框架相比,Spring Boot 允许你使用极少甚至无需任何 XML 配置来启动一个应用,让你的代码库更加整洁。
  5. 应用监控: Spring Boot Actuator 提供了一套现成的应用监控和管理功能,可以帮助你监视应用的运行状态和各种指标。

安装步骤

  1. 访问 Spring Initializr: 打开 Spring Initializr,这是一个在线工具,可以帮助你快速生成 Spring Boot 项目结构。
  2. 选择项目设置:
  • 项目类型: Maven 或 Gradle。Maven 是传统选择,而 Gradle 提供了更现代的构建工具体验。
  • Spring Boot 版本: 通常选择最新稳定版本。
  • 项目元数据: 如 Group、Artifact 等,这些将成为你的项目唯一标识。
  1. 添加起步依赖:
  • 选择你所需的起步依赖,例如 spring-boot-starter-web 用于创建 web 应用。
  1. 生成项目:
  • 生成并下载项目压缩文件。
  • 解压缩并使用你喜欢的 IDE(如 IntelliJ IDEA、Eclipse)打开。

配置和运行

  1. 配置应用属性:
  • application.propertiesapplication.yml 文件中设置应用的配置,如端口号、数据库配置等。
  1. 编写业务逻辑:
  • 创建模型(Model)、视图(View)和控制器(Controller)等组件。
  1. 运行应用:
  • 直接在 IDE 中运行应用,或者在命令行中使用 mvn spring-boot:rungradle bootRun 命令启动应用。

通过掌握这些基础知识,你就能够顺利地开始你的 Spring Boot 旅程,并为集成 Spring Security 做好准备。这就像是为你的软件开发之旅装上了一个涡轮增压器!接下来的章节将带你深入到更具挑战性的 Spring Security 领域,准备好了吗?让我们开始吧!

2.1.2 主要案例:创建基本的 Spring Boot 应用

在这个案例中,我们将一步步创建一个基本的 Spring Boot 应用程序。这就像是在建造你自己的数字王国的第一块砖。

案例 Demo

假设我们正在开发一个简单的博客应用,它将有一个页面来显示一条欢迎信息。

步骤 1:项目初始化

  1. 访问 Spring Initializr
  2. 选择你的项目设置,例如 Maven 作为构建工具和 Java 作为编程语言。
  3. 选择 Spring Boot 的最新稳定版本。
  4. 在依赖中添加 spring-boot-starter-web
  5. 点击“生成”,下载项目压缩包。

步骤 2:项目结构

  1. 解压缩下载的文件。
  2. 使用你喜欢的 IDE(例如 IntelliJ IDEA 或 Eclipse)打开项目。
  3. 查看项目结构,主要关注以下目录:
  • src/main/java: 存放 Java 源代码。
  • src/main/resources: 存放资源文件,如配置文件。

步骤 3:编写 Hello World 控制器

  1. src/main/java 下,找到主应用程序类(通常命名为 Application 或与你的项目名称相同)。
  2. 创建一个新的包,例如 com.example.blog
  3. 在该包中创建一个新的 Java 类 HelloController
package com.example.blog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
    @GetMapping("/")
    public String hello() {
        return "Welcome to the Blog!";
    }
}

步骤 4:运行应用程序

  1. 回到主应用程序类,并运行应用。
  2. 打开浏览器,访问 http://localhost:8080
  3. 你应该看到页面上显示“Welcome to the Blog!”。

再添加一个简单的服务

假设我们想要在应用中添加一个服务来处理一些业务逻辑。

案例 Demo:

  1. 创建服务类:
  • com.example.blog 包下创建一个新的类 BlogService
package com.example.blog;
import org.springframework.stereotype.Service;
@Service
public class BlogService {
    public String getWelcomeMessage() {
        return "Welcome to the Blog!";
    }
}
  1. 修改控制器以使用服务:
  • 注入 BlogServiceHelloController 并使用它。
@RestController
public class HelloController {
    private final BlogService blogService;
    public HelloController(BlogService blogService) {
        this.blogService = blogService;
    }
    @GetMapping("/")
    public String hello() {
        return blogService.getWelcomeMessage();
    }
}
  1. 运行并测试:
  • 再次运行应用程序,并验证服务是否正确返回消息。

还可以整合数据库

让我们进一步扩展应用,通过整合数据库来存储和检索数据。

案例 Demo:

  1. 添加数据库依赖:
  • pom.xml 中添加 spring-boot-starter-data-jpa 和内嵌数据库(如 H2)的依赖。
  1. 配置数据库:
  • application.properties 中配置数据库。
  1. 创建实体和仓库:
  • 定义一个实体类 BlogPost 和一个仓库接口 BlogPostRepository
  1. 修改服务以使用数据库:
  • 更新 BlogService 以使用 BlogPostRepository
  1. 运行并测试:
  • 测试应用能否正确地存取数据。

通过这个案例,你将了解到如何从零开始创建一个 Spring Boot 应用,并逐步扩展其功能,从一个简单的 “Hello World” 到集成服务和数据库。这将为你打下坚实的基础,为进一步探索 Spring Security 的世界做好准备。

2.1.3 拓展案例 1:添加数据库支持

在这个案例中,我们将在 Spring Boot 应用中添加数据库支持,以增强其数据持久化能力。我们将构建一个简单的博客应用,其中包括保存和检索博客文章的功能。

案例 Demo

假设我们的博客应用需要保存博客文章到数据库,并能够从数据库中检索这些文章。

步骤 1:添加数据库依赖

  1. pom.xml 中添加 spring-boot-starter-data-jpa 依赖和一个数据库连接池依赖,例如 H2。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

步骤 2:配置数据库

  1. application.properties 中配置 H2 数据库。
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

步骤 3:创建实体和仓库

  1. 创建一个实体类 BlogPost
package com.example.blog;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class BlogPost {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String title;
    private String content;
    // 省略 getter 和 setter
}
  1. 创建一个继承自 JpaRepository 的仓库接口 BlogPostRepository
package com.example.blog;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BlogPostRepository extends JpaRepository<BlogPost, Long> {
}

步骤 4:创建服务类和控制器

  1. 创建一个服务类 BlogService 来处理业务逻辑。
package com.example.blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BlogService {
    private final BlogPostRepository repository;
    @Autowired
    public BlogService(BlogPostRepository repository) {
        this.repository = repository;
    }
    public BlogPost saveBlogPost(BlogPost post) {
        return repository.save(post);
    }
    public List<BlogPost> getAllBlogPosts() {
        return repository.findAll();
    }
}
  1. HelloController 中添加新的端点。
package com.example.blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class BlogController {
    private final BlogService blogService;
    @Autowired
    public BlogController(BlogService blogService) {
        this.blogService = blogService;
    }
    @PostMapping("/posts")
    public BlogPost addBlogPost(@RequestBody BlogPost post) {
        return blogService.saveBlogPost(post);
    }
    @GetMapping("/posts")
    public List<BlogPost> getAllBlogPosts() {
        return blogService.getAllBlogPosts();
    }
}

步骤 5:运行和测试

  1. 运行应用程序。
  2. 使用 REST 客户端或浏览器访问 http://localhost:8080/posts 来查看所有博客文章,或通过 POST 请求向 /posts 添加新的博客文章。

通过这个案例,你将学会如何在 Spring Boot 应用中添加和配置数据库支持,创建实体和仓库,并通过服务类和控制器与数据库交互。这些步骤为构建具有数据持久化功能的应用提供了基础,使你的 Spring Boot 之旅更加丰富多彩。

2.1.4 拓展案例 2:整合外部服务

在这个案例中,我们将演示如何将外部服务整合到 Spring Boot 应用中。我们将以集成一个简单的邮件发送服务为例。

案例 Demo

假设我们的 Spring Boot 应用需要发送欢迎邮件给新注册的用户。

步骤 1:添加邮件服务依赖

  1. pom.xml 中添加 spring-boot-starter-mail 依赖。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

步骤 2:配置邮件服务器

  1. application.properties 中配置邮件服务器的属性。这里我们以 Gmail 为例:
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

步骤 3:创建邮件服务类

  1. 创建一个 EmailService 类来封装邮件发送逻辑。
package com.example.blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;
    public void sendWelcomeEmail(String to, String username) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("noreply@example.com");
        message.setTo(to);
        message.setSubject("Welcome to the Blog!");
        message.setText("Hello " + username + ",\nWelcome to our blog!");
        mailSender.send(message);
    }
}

步骤 4:在应用中使用邮件服务

  1. 创建一个控制器来使用 EmailService 发送邮件。
package com.example.blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
    private final EmailService emailService;
    @Autowired
    public UserController(EmailService emailService) {
        this.emailService = emailService;
    }
    @PostMapping("/register")
    public String registerUser(@RequestParam String email, @RequestParam String username) {
        // 注册用户的逻辑...
        emailService.sendWelcomeEmail(email, username);
        return "User registered successfully!";
    }
}

步骤 5:运行和测试

  1. 运行你的 Spring Boot 应用。
  2. 使用 POST 请求向 /users/register 发送一个包含邮件地址和用户名的请求。
  3. 检查指定的邮箱,确认是否收到了欢迎邮件。

通过这个案例,你将学会如何在 Spring Boot 应用中集成外部服务,如邮件服务。这不仅增强了你的应用功能,还提高了用户体验。整合外部服务是构建现代应用的关键步骤,它能让你的应用更加丰富和动态。

2.2 集成 Spring Security

2.2.1 基础知识详解

集成 Spring Security 到你的 Spring Boot 应用中是一项关键任务,它保障了应用的安全性和数据保护。在此过程中,你将了解到 Spring Security 的核心概念和实现方法。

Spring Security 的核心组件

  1. 过滤器链(Filter Chains):
  • Spring Security 使用一系列过滤器来处理不同的安全考虑。这些过滤器负责执行认证、授权等安全操作。
  1. 认证(Authentication):
  • 认证是确认用户身份的过程。Spring Security 提供多种认证方式,如内存认证、数据库认证、LDAP 认证等。
  1. 授权(Authorization):
  • 授权是控制已认证用户访问应用程序资源的过程。Spring Security 支持基于角色的访问控制(RBAC)和基于表达式的访问控制。
  1. 用户详情服务(UserDetailsService):
  • UserDetailsService 接口用于根据用户名加载用户的数据。它通常用于从数据库中加载用户信息。
  1. 密码编码器(PasswordEncoder):
  • Spring Security 强调对密码进行加密存储。PasswordEncoder 接口用于定义密码的加密方式。

Spring Security 的配置

  1. 创建 SecurityConfig 类:
  • 通过扩展 WebSecurityConfigurerAdapter 类并覆写其方法,你可以自定义应用程序的安全配置。
  1. 定义认证规则:
  • configure(AuthenticationManagerBuilder auth) 方法中定义认证规则。
  1. 定义授权规则:
  • configure(HttpSecurity http) 方法中定义哪些路径应该受保护,哪些路径应该公开访问。
  1. 自定义登录和注销:
  • Spring Security 允许自定义登录和注销行为,你可以指定登录页面、默认成功登录跳转路径等。

通过理解这些基础概念和配置步骤,你将能够为你的应用添加一个强大而灵活的安全层。这不仅保护了你的应用免受未经授权的访问,还为用户提供了安全的交互环境。

2.2.2 主要案例:基本的安全配置

在这个案例中,我们将通过一个实际的示例来展示如何在 Spring Boot 应用中实现基本的安全配置。

案例 Demo

我们将构建一个简单的博客应用,它允许用户查看文章列表,但只有注册用户才能查看文章详情。

步骤 1:配置安全依赖

  1. 在你的 Spring Boot 项目的 pom.xml 中添加 Spring Security 依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

步骤 2:创建安全配置类

  1. 创建一个新的 Java 类 SecurityConfig 并扩展 WebSecurityConfigurerAdapter
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/", "/posts").permitAll()
            .antMatchers("/post/*").authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll();
    }
}
  1. 在这里,我们配置了 URL 模式的安全性。任何人都可以访问主页 (/) 和文章列表 (/posts),但只有认证用户可以访问文章详情(例如 /post/1)。

步骤 3:创建控制器

  1. 创建一个控制器 BlogController 来处理 HTTP 请求。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class BlogController {
    @GetMapping("/")
    public String home() {
        return "home";
    }
    @GetMapping("/posts")
    public String posts() {
        return "posts";
    }
    @GetMapping("/post/{id}")
    public String postDetails() {
        return "post-details";
    }
    @GetMapping("/login")
    public String login() {
        return "login";
    }
}
  1. 这里,我们定义了不同的路由和它们对应的视图。

步骤 4:创建视图

  1. 创建相应的 HTML 文件(如 home.html, posts.html, post-details.html, login.html)在 src/main/resources/templates 目录下。

步骤 5:运行应用程序

  1. 运行你的 Spring Boot 应用。
  2. 在浏览器中访问 http://localhost:8080,尝试点击不同的链接,并观察安全配置的效果。

通过这个案例,你将学会如何在 Spring Boot 应用中添加基本的 Spring Security 配置。这样做不仅提高了应用的安全性,还为今后添加更复杂的安全功能奠定了基础。

第2章 Spring Security 的环境设置与基础配置(2024 最新版)(下)+https://developer.aliyun.com/article/1487142

目录
相关文章
|
1天前
|
Java 应用服务中间件 Maven
ContextLoaderListener在Spring应用中的作用与配置方法
ContextLoaderListener在Spring应用中的作用与配置方法
|
2天前
|
存储 Java 开发工具
Spring Boot中的配置中心实现
Spring Boot中的配置中心实现
|
2天前
|
IDE Java 数据库连接
如何使用Spring Boot Profiles进行环境配置管理
如何使用Spring Boot Profiles进行环境配置管理
|
2天前
|
Java 应用服务中间件 测试技术
Spring Boot中最佳实践:数据源配置详解
Spring Boot中最佳实践:数据源配置详解
|
2天前
|
安全 Java 数据安全/隐私保护
使用Spring Boot和Spring Security保护你的应用
使用Spring Boot和Spring Security保护你的应用
|
2天前
|
存储 Java 数据库
Spring Boot中如何配置和使用多数据源
Spring Boot中如何配置和使用多数据源
|
2天前
|
监控 安全 Java
Spring Boot中的安全性配置详解
Spring Boot中的安全性配置详解
|
2天前
|
Java UED Spring
Spring Boot中的国际化配置
Spring Boot中的国际化配置
|
2天前
|
监控 Java 开发者
Spring Boot中的热部署配置
Spring Boot中的热部署配置
|
2天前
|
Java API Spring
Spring Boot中配置Swagger用于API文档
Spring Boot中配置Swagger用于API文档