《Spring Security 简易速速上手小册》第3章 用户认证机制(2024 最新版)

news2024/9/25 7:21:20

在这里插入图片描述

文章目录

  • 3.1 认证流程
    • 3.1.1 基础知识详解
      • 认证流程的核心概念
      • 认证流程的步骤
    • 3.1.2 主要案例:内存用户认证
      • 案例 Demo:快速启动你的 Spring Boot 守护程序
    • 3.1.3 拓展案例 1:数据库用户认证
      • 案例 Demo:让数据库守护你的秘密
    • 3.1.4 拓展案例 2:集成 OAuth2 认证
      • 案例 Demo
  • 3.2 配置用户详细信息服务
    • 3.2.1 基础知识详解
      • 用户详细信息服务 (`UserDetailsService`)
      • 密码编码 (`PasswordEncoder`)
      • 认证管理器 (`AuthenticationManager`)
      • 自定义用户详细信息服务
    • 3.2.2 主要案例:自定义数据库用户详细信息服务
      • 案例 Demo
    • 3.2.3 拓展案例 1:内存中的用户存储
      • 案例 Demo
    • 3.2.4 拓展案例 2:使用 JdbcUserDetailsManager
      • 案例 Demo
  • 3.3 自定义认证逻辑
    • 3.3.1 基础知识详解
      • 认证管理器 (`AuthenticationManager`)
      • 认证提供者 (`AuthenticationProvider`)
      • 用户详细信息服务 (`UserDetailsService`)
      • 密码编码 (`PasswordEncoder`)
      • 自定义认证逻辑的意义
    • 3.3.2 主要案例:添加验证码校验
      • 案例 Demo
    • 3.3.3 拓展案例 1:实现基于短信的认证
      • 案例 Demo
    • 3.3.4 拓展案例 2:集成第三方认证服务
      • 案例 Demo
      • 拓展:自定义 OAuth2 登录行为

3.1 认证流程

在 Spring Security 的世界里,认证流程是核心的安全机制,用于确认一个请求是否来自一个有效的用户。这个过程可以比作一道门槛,只有拥有正确钥匙的人才能进入。

3.1.1 基础知识详解

在深入探索用户认证机制之前,让我们首先建立一些基础知识,确保我们都在同一页面上。用户认证在应用安全中扮演着至关重要的角色,它就像是一道门槛,确保只有拥有正确密钥的人才能进入。

认证流程的核心概念

  1. 认证(Authentication):

    • 这是确定某人是谁的过程。在网络安全中,它通常涉及用户名和密码,但也可以包括其他方法,如二因素认证、生物识别等。
  2. 授权(Authorization):

    • 一旦用户被认证,接下来就是确定他们有权访问的资源或执行的操作。简单来说,就是确定他们可以做什么。
  3. 凭证(Credentials):

    • 通常是指证明用户身份的信息,如用户名和密码、安全令牌等。
  4. 主体(Principal):

    • 在安全服务中,主体通常指可以在应用中执行操作的用户、设备或其他系统。
  5. 认证管理器(AuthenticationManager):

    • Spring Security 中的接口,负责协调认证过程。
  6. 用户详情服务(UserDetailsService):

    • 用于从指定的数据源(例如数据库、LDAP)加载用户信息的接口。
  7. 密码编码器(PasswordEncoder):

    • 负责密码加密和验证,以确保存储和比较密码的安全性。

认证流程的步骤

用户认证流程通常包括以下步骤:

  1. 用户提交凭证:

    • 用户通过登录表单或其他认证机制提交他们的凭证。
  2. 加载用户详情:

    • 系统利用 UserDetailsService 根据提交的凭证(通常是用户名)加载用户的详细信息。
  3. 凭证验证:

    • 使用 PasswordEncoder 等工具验证用户提交的凭证(如密码)是否与存储的凭证匹配。
  4. 创建认证令牌:

    • 一旦用户被验证,系统会创建一个认证令牌(Authentication 对象),表示用户的认证状态。
  5. 设置安全上下文:

    • 认证令牌被存储在安全上下文(SecurityContextHolder)中,以便在应用的后续处理中使用。

通过理解这些基础知识,你现在应该对 Spring Security 中的用户认证流程有了一个清晰的概念。这为我们深入探索如何在实际应用中实现和测试不同类型的认证机制奠定了坚实的基础。

3.1.2 主要案例:内存用户认证

让我们通过一个实际的示例来演示如何在 Spring Boot 应用中实现基于内存的用户认证。这种方法非常适合开发和测试环境,让我们快速启动并运行,无需配置复杂的外部数据源。

案例 Demo:快速启动你的 Spring Boot 守护程序

想象你正在创建一个神秘的守护程序,这个程序守护着一个包含古老知识的图书馆。为了进入图书馆,读者必须通过一个古老的仪式(也就是登录过程)。但在这个仪式中,我们将使用现代的 Spring Security 魔法来识别访客。

步骤 1:准备你的魔法工具

确保你的 pom.xml 中已经添加了 Spring Security 的依赖。

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

步骤 2:铸造你的魔法咒语

创建一个配置类 SecurityConfig 来定义你的安全配置。在这个咒语中,我们将定义哪些用户有权访问我们神秘的图书馆。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("wizard").password(passwordEncoder().encode("ancientSecret")).roles("WIZARD")
            .and()
            .withUser("apprentice").password(passwordEncoder().encode("learning")).roles("APPRENTICE");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

在这段咒语中,我们定义了两个用户:“wizard” 和 “apprentice”,他们分别拥有不同的秘密和角色。

步骤 3:守护你的图书馆入口

现在,让我们创建一个简单的控制器 LibraryController,来守护我们的图书馆入口。

@RestController
public class LibraryController {

    @GetMapping("/")
    public String welcome() {
        return "Welcome to the Ancient Library!";
    }

    @GetMapping("/secret")
    public String secret() {
        return "Behold the Ancient Secrets!";
    }
}

这里,任何人都可以被欢迎进入图书馆,但只有通过了认证的访客才能看到古老的秘密。

步骤 4:召唤你的应用守护程序

现在,运行你的 Spring Boot 应用。访问 http://localhost:8080/ 将显示欢迎信息。尝试访问 http://localhost:8080/secret,如果未登录,你将被重定向到登录页面。

恭喜你,你已经成功实现了基于内存的用户认证,保护了你神秘图书馆的秘密!通过这个简单的案例,你学会了如何使用 Spring Security 进行基本的安全配置,现在你的应用已经有了一个强大的守护者。

3.1.3 拓展案例 1:数据库用户认证

现在,让我们的守护程序升级,使它能够通过一个神秘的图书管理员名单(也就是数据库)来识别进入图书馆的访客。这个名单记录着每位图书管理员的名字和他们守护的秘密(用户名和密码)。

案例 Demo:让数据库守护你的秘密

假设我们的应用已经有了一些基本的用户认证机制,现在我们要将用户信息存储在数据库中,而不是静静地躺在内存里。

步骤 1:添加你的数据库和 JPA 魔法工具

首先,确保你的 pom.xml 包含了对 Spring 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:设计你的图书管理员名单

创建一个 Librarian 实体来代表你的用户,并设计一个 LibrarianRepository 来访问数据库中的用户信息。

@Entity
public class Librarian {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;
    private String password;

    // Standard getters and setters
}

public interface LibrarianRepository extends JpaRepository<Librarian, Long> {
    Optional<Librarian> findByUsername(String username);
}

步骤 3:告诉你的守护程序如何读取名单

实现 UserDetailsService 接口,让 Spring Security 知道如何通过 LibrarianRepository 从数据库中查找用户。

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private LibrarianRepository librarianRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Librarian librarian = librarianRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("Librarian not found: " + username));

        return new User(librarian.getUsername(), librarian.getPassword(), new ArrayList<>());
    }
}

步骤 4:配置你的保安来使用这个名单

在你的 SecurityConfig 中,配置 AuthenticationManagerBuilder 以使用你的 CustomUserDetailsService

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

步骤 5:召唤并测试你的守护程序

运行你的 Spring Boot 应用,并尝试使用存储在数据库中的用户信息进行登录。你可以通过 H2 Console 或其他数据库管理工具添加用户到你的 Librarian 表中来测试。

通过这个案例,你已经让你的应用升级,现在它可以通过数据库来认证用户了。这为保护你神秘的图书馆添加了一层额外的安全措施,确保只有真正的图书管理员能够进入。

3.1.4 拓展案例 2:集成 OAuth2 认证

在这个案例中,我们将通过集成 Lightweight Directory Access Protocol (LDAP) 认证来实现企业级的用户管理和认证机制。LDAP 是广泛用于企业环境中的用户和组织信息的目录服务协议,它允许应用以统一的方式查询和管理用户信息。

案例 Demo

假设你正在开发一个需要对接企业LDAP服务器进行用户认证的Spring Boot应用。以下是如何实现LDAP认证的步骤:

步骤 1:添加 LDAP 依赖

  1. pom.xml 中添加 Spring LDAP 的依赖。

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

步骤 2:配置 LDAP

  1. application.propertiesapplication.yml 中配置 LDAP 连接信息,包括URL、用户DN(Distinguished Name)模式等。

    spring.ldap.urls=ldap://localhost:8389
    spring.ldap.base=dc=example,dc=com
    spring.ldap.username=cn=admin,dc=example,dc=com
    spring.ldap.password=admin
    spring.ldap.user.dn-pattern=uid={0},ou=people
    

这些配置指定了LDAP服务器的地址、基础搜索路径、用于绑定(登录)的管理员用户名和密码,以及用于搜索用户的DN模式。

步骤 3:实现 LDAP 认证

  1. 创建一个安全配置类 WebSecurityConfig,使用LDAP进行认证。

    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    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 WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth
                .ldapAuthentication()
                .userDnPatterns("uid={0},ou=people")
                .groupSearchBase("ou=groups")
                .contextSource()
                .url("ldap://localhost:8389/dc=example,dc=com")
                .and()
                .passwordCompare()
                .passwordEncoder(new BCryptPasswordEncoder())
                .passwordAttribute("userPassword");
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin();
        }
    }
    

这里我们配置了LDAP认证,指定用户和组的搜索基础,以及密码比对的策略。

步骤 4:运行和测试

  1. 启动你的 Spring Boot 应用。
  2. 访问应用中的受保护资源,例如 http://localhost:8080/
  3. 系统应该会重定向到登录页面。尝试使用 LDAP 服务器中的用户凭证进行登录。

通过整合 LDAP 认证,你的应用现在可以利用现有的企业级用户目录进行安全的用户认证,从而实现统一的身份管理和访问控制。这种方法特别适用于大型企业应用,能够大大简化用户管理和应用部署的复杂性。

3.2 配置用户详细信息服务

在 Spring Security 中,用户详细信息服务(UserDetailsService)是一个核心接口,用于从你选择的数据源加载用户信息。通过实现这个接口,Spring Security 可以在进行认证时获取到用户的详细信息,如用户名、密码和授权。

3.2.1 基础知识详解

在 Spring Security 中,用户详细信息服务(UserDetailsService)扮演着至关重要的角色。它负责从指定的数据源中加载用户的详细信息,这些信息随后被用于在认证过程中验证用户的身份。理解并正确配置用户详细信息服务对于建立一个安全的 Spring 应用来说是必不可少的。

用户详细信息服务 (UserDetailsService)

UserDetailsService 是一个核心接口,定义了一个方法 loadUserByUsername(String username),该方法接收一个用户名作为参数,并返回一个 UserDetails 实例,其中包含了用户的详细信息。如果指定用户名的用户不存在,则抛出一个 UsernameNotFoundException

密码编码 (PasswordEncoder)

为了安全地存储用户密码,Spring Security 提供了密码编码器的概念。PasswordEncoder 接口定义了密码编码(加密)和匹配(验证)方法。最常用的实现是 BCryptPasswordEncoder,它使用 BCrypt 强哈希算法来加密密码。使用密码编码器可以确保即使数据被泄露,攻击者也无法轻易地解码用户密码。

认证管理器 (AuthenticationManager)

AuthenticationManager 是 Spring Security 认证架构的入口点。它定义了一个 authenticate(Authentication authentication) 方法,用于尝试对输入的认证信息进行认证。在配置 WebSecurityConfigurerAdapter 时,通过覆写 configure(AuthenticationManagerBuilder auth) 方法来设置应用的认证管理器,包括指定用户详细信息服务和密码编码器。

自定义用户详细信息服务

虽然 Spring Security 提供了基于内存和基于JDBC的用户详细信息服务实现,但在许多情况下,你可能需要从不同的数据源加载用户信息,如使用 JPA 从关系型数据库或者连接到 LDAP 服务器。在这种情况下,你可以通过实现 UserDetailsService 接口来提供自定义的用户详细信息服务。

自定义实现通常会涉及到以下步骤:

  1. 实现 UserDetailsService 接口:创建一个类来实现 UserDetailsService 接口,提供 loadUserByUsername 方法的具体实现,用于从你选择的数据源中加载用户信息。

  2. 配置认证管理器:在你的安全配置中(一个扩展自 WebSecurityConfigurerAdapter 的类),通过覆写 configure(AuthenticationManagerBuilder auth) 方法来使用你的自定义 UserDetailsService

  3. 使用密码编码器:为了安全地处理密码,你应该在 configure(AuthenticationManagerBuilder auth) 方法中配置一个密码编码器(如 BCryptPasswordEncoder)。

通过深入了解和配置用户详细信息服务,你可以确保你的 Spring 应用在处理用户认证时既灵活又安全。

3.2.2 主要案例:自定义数据库用户详细信息服务

在这个案例中,我们将通过自定义 UserDetailsService 实现,从数据库加载用户信息以进行认证。这对于需要动态管理用户信息的应用尤其重要。

案例 Demo

假设我们正在开发一个需要用户认证的 Spring Boot 应用,并且希望用户信息存储在关系型数据库中。

步骤 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 中配置数据库连接。

    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
    

步骤 3: 创建用户实体和仓库

  1. 定义一个 User 实体类。

    @Entity
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        private String username;
        private String password;
        // Constructors, Getters, and Setters
    }
    
  2. 创建 UserRepository 接口。

    public interface UserRepository extends JpaRepository<User, Long> {
        Optional<User> findByUsername(String username);
    }
    

步骤 4: 实现 UserDetailsService

  1. 创建 CustomUserDetailsService 类。

    @Service
    public class CustomUserDetailsService implements UserDetailsService {
        @Autowired
        private UserRepository userRepository;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + username));
            return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
        }
    }
    

步骤 5: 配置安全性

  1. 创建 SecurityConfig 类,配置自定义的 UserDetailsService 和密码编码器。

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private CustomUserDetailsService userDetailsService;
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
        }
    }
    

通过这个案例,你将学会如何自定义 UserDetailsService 以从数据库加载用户信息,并在 Spring Security 中使用这些信息进行认证。这种方法为你提供了灵活性来管理用户信息,并且能够确保你的应用安全性。

3.2.3 拓展案例 1:内存中的用户存储

对于开发环境或小型应用,可能你只需要一个简单的用户存储而不想引入外部数据库的复杂性。在这种情况下,Spring Security 允许你在内存中定义用户列表,这是一个快速启动和测试安全配置的好方法。

案例 Demo

让我们创建一个 Spring Boot 应用,其中用户认证信息存储在内存中,以简化认证流程。

步骤 1: 添加 Spring Security 依赖

首先,确保你的 pom.xml 包含了 Spring Security 的起步依赖。

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

步骤 2: 配置内存中的用户存储

创建一个安全配置类 SecurityConfig,在这个类中,你将定义用户的认证信息。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("password").roles("USER")
            .and()
            .withUser("admin").password("admin").roles("ADMIN");
    }

    @SuppressWarnings("deprecation")
    @Bean
    public PasswordEncoder passwordEncoder() {
        // WARNING: This is only for demonstration purposes and should not be used in production
        return NoOpPasswordEncoder.getInstance();
    }
}

在这个配置中,我们定义了两个用户,一个是普通用户,另一个是管理员,都使用了不安全的密码编码器 NoOpPasswordEncoder 来避免密码加密。注意NoOpPasswordEncoder 已被弃用,仅用于演示目的,生产环境中应使用强密码编码器如 BCryptPasswordEncoder

步骤 3: 测试认证

运行你的 Spring Boot 应用,并尝试访问任何受保护的资源。你将被重定向到登录页面,此时可以使用上面定义的用户凭证进行登录。

通过这个简单的案例,你可以快速地在 Spring Boot 应用中实现用户认证功能,而不需要配置外部数据源。这对于原型开发或小型应用来说是一个理想的选择。

3.2.4 拓展案例 2:使用 JdbcUserDetailsManager

当你的应用需要从关系型数据库中加载用户信息进行认证时,Spring Security 提供了一个方便的方式来实现这一需求——使用 JdbcUserDetailsManager。这个方法不仅支持用户信息的加载,还支持通过 JDBC 进行用户的增加、删除和修改操作。

案例 Demo

我们将构建一个 Spring Boot 应用,使用 JdbcUserDetailsManager 从数据库加载用户信息进行认证。

步骤 1: 添加依赖

在你的 pom.xml 文件中添加 Spring Boot 的数据 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: 配置数据源和安全配置

application.properties 文件中配置你的数据库连接,以及启用 H2 控制台。

spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
spring.sql.init.platform=h2

创建安全配置类 SecurityConfig,配置 JdbcUserDetailsManager

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService(DataSource dataSource) {
        return new JdbcUserDetailsManager(dataSource);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .jdbcAuthentication()
            .dataSource(dataSource())
            .usersByUsernameQuery("select username, password, enabled from users where username=?")
            .authoritiesByUsernameQuery("select username, authority from authorities where username=?")
            .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .and()
            .httpBasic();
    }
}

步骤 3: 初始化用户数据

通常,你需要预先在数据库中创建 usersauthorities 表,并插入一些测试用户。你可以使用 Spring SQL 初始化特性来自动完成这一步骤。

src/main/resources/schema.sql 中定义表结构:

CREATE TABLE users (
  username VARCHAR(50) NOT NULL PRIMARY KEY,
  password VARCHAR(100) NOT NULL,
  enabled BOOLEAN NOT NULL
);

CREATE TABLE authorities (
  username VARCHAR(50) NOT NULL,
  authority VARCHAR(50) NOT NULL,
  FOREIGN KEY (username) REFERENCES users(username)
);

src/main/resources/data.sql 中插入测试数据:

INSERT INTO users (username, password, enabled) VALUES ('user', '{bcrypt}加密后的密码', true);
INSERT INTO authorities (username, authority) VALUES ('user', 'ROLE_USER');

确保将 {bcrypt}加密后的密码 替换为使用 BCryptPasswordEncoder 加密的密码。

步骤 4: 测试认证

启动应用并访问任何受保护的 URL,系统应重定向你到登录页面。使用步骤 3 中定义的用户凭证进行登录,验证认证流程是否按预期工作。

通过使用 JdbcUserDetailsManager,你可以轻松地将 Spring Security 与数据库用户存储集成,实现复杂的认证和用户管理功能。这种方式适合需要持久化用户信息的中大型应用。

3.3 自定义认证逻辑

在 Spring Security 中,定制认证逻辑可以让你实现更加复杂和安全的认证机制,比如添加验证码校验、实现多因素认证等。Spring Security 提供了灵活的扩展点,使得定制认证过程变得可行。

3.3.1 基础知识详解

认证管理器 (AuthenticationManager)

  • AuthenticationManager 是 Spring Security 认证机制的中心接口,负责协调认证过程。
  • 它定义了一个 authenticate(Authentication authentication) 方法,用于尝试对输入的认证信息进行认证。

认证提供者 (AuthenticationProvider)

  • AuthenticationProvider 接口定义了实际执行认证逻辑的方法。
  • 每个 AuthenticationProvider 都能处理特定类型的认证请求。例如,你可以有一个专门处理用户名和密码认证的提供者,另一个处理基于短信验证码的认证。

用户详细信息服务 (UserDetailsService)

  • UserDetailsService 是一个用于加载用户特定数据的核心接口。它只有一个方法 loadUserByUsername(String username),用于根据用户名查找 UserDetails 对象。
  • UserDetails 对象包含了一些基本的用户信息,如用户名、密码、权限等。

密码编码 (PasswordEncoder)

  • 在认证过程中,用户提交的密码需要与存储在系统中的密码进行比对。为了安全起见,存储的密码通常是加密过的。
  • PasswordEncoder 接口定义了加密和匹配用户密码的方法。使用强加密算法(如 BCrypt)可以有效防止密码被破解。

自定义认证逻辑的意义

  • 安全性提升:通过自定义认证逻辑,开发者可以引入额外的安全措施,如验证码验证、多因素认证等,进一步增强应用的安全性。
  • 灵活性和扩展性:每个应用的安全需求都是独特的。Spring Security 的可扩展性允许开发者根据自己的需求定制认证过程。
  • 集成第三方服务:在现代的应用中,常常需要集成第三方认证服务(如社交登录)。自定义认证逻辑使得这种集成变得可行。

通过深入理解和应用上述基础知识,开发者可以充分利用 Spring Security 提供的强大功能,实现既安全又符合业务需求的认证机制。

3.3.2 主要案例:添加验证码校验

在这个案例中,我们将实现一个包含验证码校验的自定义认证流程,以增强登录过程的安全性。验证码校验是一种常见的防止自动化攻击(如暴力破解、机器人登录)的手段。

案例 Demo

假设我们的 Spring Boot 应用有一个登录表单,我们想在用户提交表单时验证一个验证码字段。

步骤 1: 集成验证码服务

首先,假设你有一个服务来生成和验证验证码,我们将其称为 CaptchaService

@Service
public class CaptchaService {

    public boolean validateCaptcha(String sessionId, String captcha) {
        // 模拟验证码校验逻辑
        // 在实际应用中,应该根据 sessionId 查找预先存储的验证码,并与用户输入的 captcha 进行比对
        return "expectedCaptcha".equals(captcha);
    }
}

步骤 2: 自定义认证过滤器

创建一个自定义的认证过滤器 CustomAuthenticationFilter,在尝试认证之前校验验证码。

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private CaptchaService captchaService;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        String captcha = request.getParameter("captcha");
        String sessionId = request.getSession().getId();

        if (!captchaService.validateCaptcha(sessionId, captcha)) {
            throw new AuthenticationServiceException("验证码错误");
        }

        return super.attemptAuthentication(request, response);
    }
}

步骤 3: 配置自定义过滤器

在你的安全配置类中,注册自定义的认证过滤器并设置其在 UsernamePasswordAuthenticationFilter 之前执行。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationFilter customAuthenticationFilter;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // 配置用户认证逻辑,例如使用 inMemoryAuthentication 或其他
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 其他配置...
            .addFilterBefore(customAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    
    @Bean
    public CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
      CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
      filter.setAuthenticationManager(authenticationManagerBean());
      return filter;
    }
}

步骤 4: 测试验证码功能

启动应用并访问登录页面。尝试不输入验证码或输入错误的验证码提交登录表单,应该被阻止并提示验证码错误。

通过实现这个案例,你将学会如何在 Spring Security 的认证过程中加入额外的校验步骤,如验证码校验,以增强应用的安全性。这种方法为防止自动化攻击提供了一层额外的保护。

3.3.3 拓展案例 1:实现基于短信的认证

在这个案例中,我们将通过实现基于短信验证码的认证流程来增强应用的安全性。这种方法适合于需要额外安全措施的场景,例如金融应用或敏感数据的访问控制。

案例 Demo

步骤 1: 创建短信验证码服务

首先,创建一个服务来发送和验证短信验证码,这里我们称之为 SmsCodeService

@Service
public class SmsCodeService {

    private final Map<String, String> smsCodeStorage = new ConcurrentHashMap<>();

    public void sendSmsCode(String mobile, String code) {
        // 实际项目中应调用短信服务提供商的API发送短信
        // 这里仅做模拟
        smsCodeStorage.put(mobile, code);
        System.out.println("Sending SMS code " + code + " to " + mobile);
    }

    public boolean validateSmsCode(String mobile, String code) {
        String validCode = smsCodeStorage.get(mobile);
        return code.equals(validCode);
    }
}

步骤 2: 定义短信认证令牌

创建一个 SmsAuthenticationToken 类来表示短信认证的令牌。

public class SmsAuthenticationToken extends AbstractAuthenticationToken {

    private final Object principal;
    private String code;

    public SmsAuthenticationToken(String mobile, String code) {
        super(null);
        this.principal = mobile;
        this.code = code;
        setAuthenticated(false);
    }

    public SmsAuthenticationToken(String mobile, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = mobile;
        this.code = null;
        super.setAuthenticated(true); // must use super, as we override
    }

    @Override
    public Object getCredentials() {
        return code;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }
}

步骤 3: 实现短信认证提供者

创建一个 SmsAuthenticationProvider 类来实现短信验证码的认证逻辑。

@Component
public class SmsAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private SmsCodeService smsCodeService;

    @Autowired
    private MyUserDetailsService myUserDetailsService; // 自定义的UserDetailsService实现

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
        String mobile = (String) authenticationToken.getPrincipal();
        String code = (String) authenticationToken.getCredentials();

        if (!smsCodeService.validateSmsCode(mobile, code)) {
            throw new BadCredentialsException("短信验证码错误");
        }

        UserDetails userDetails = myUserDetailsService.loadUserByMobile(mobile);
        if (userDetails == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (SmsAuthenticationToken.class.isAssignableFrom(authentication));
    }
}

步骤 4: 配置短信认证

在安全配置类中注册 SmsAuthenticationProvider

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SmsAuthenticationProvider smsAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(smsAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置安全规则
    }
}

步骤 5: 测试短信认证

启动应用并尝试使用短信验证码登录。你可以创建一个简单的登录页面,用于输入手机号和验证码,然后通过后端接口验证。

通过实现这个案例,你将能够为你的应用添加基于短信验证码的二次认证流程,提高安全性。这种认证方式在需要额外验证用户身份的场景中非常有用,尤其是在移动应用中。

3.3.4 拓展案例 2:集成第三方认证服务

在这个案例中,我们将演示如何将第三方认证服务(例如 OAuth2 提供商,如 Google 或 Facebook)集成到 Spring Boot 应用中,为用户提供更多便捷的登录选项。

案例 Demo

假设我们希望用户可以通过 Google 账户登录我们的应用。

步骤 1: 添加依赖

首先,确保你的 pom.xml 包含了 Spring Security OAuth2 客户端的起步依赖。

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

步骤 2: 配置 OAuth2 客户端

application.ymlapplication.properties 文件中配置 OAuth2 客户端信息。以下是使用 Google 作为 OAuth2 提供商的一个例子:

spring.security.oauth2.client.registration.google.client-id=your-google-client-id
spring.security.oauth2.client.registration.google.client-secret=your-google-client-secret
spring.security.oauth2.client.registration.google.scope=profile,email

你需要替换 your-google-client-idyour-google-client-secret 为你在 Google Cloud Platform 创建 OAuth2 客户端时获得的客户端 ID 和密钥。

步骤 3: 创建安全配置

创建一个安全配置类 SecurityConfig,配置使用 OAuth2 登录:

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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()
            .anyRequest().authenticated()
            .and()
            .oauth2Login();
    }
}

这个配置确保了所有请求都需要认证,并启用了 OAuth2 登录。

步骤 4: 测试 OAuth2 登录

启动应用并尝试访问任何受保护的资源。系统应该会重定向你到 Google 的登录页面。使用你的 Google 账户登录后,你将被重定向回应用,并成功访问受保护的资源。

拓展:自定义 OAuth2 登录行为

Spring Security 允许你自定义 OAuth2 登录行为,例如自定义登录成功或失败后的处理逻辑:

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .oauth2Login()
                .userInfoEndpoint()
                .oidcUserService(this.oidcUserService());
    }

    private OidcUserService oidcUserService() {
        OidcUserService service = new OidcUserService();
        service.setUserinfoCustomizer((userRequest, user) -> {
            // 自定义用户信息处理逻辑
        });
        return service;
    }
}

通过实现这个案例,你可以向你的应用添加更多的登录选项,提供更便捷的用户体验,并利用第三方服务提供的安全性。这种方法尤其适用于希望简化登录过程或提供社交登录选项的现代应用。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1489709.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

vue3三级嵌套复选框(element-plus)

一、功能描述 当选择第一级的复选框时下面所有内容全选和取消全选&#xff0c;当选择第二的复选框时第三级的所有内容全选和取消全选。只要有一个第三级的内容没有选&#xff0c;二级和一级则不能勾上。第三级内容全选上了&#xff0c;第二级复选框就钩上。第二级也是同样的道理…

【暗月安全】2021年渗透测试全套培训视频

参与培训需要遵守国家法律法规&#xff0c;相关知识只做技术研究&#xff0c;请勿用于违法用途&#xff0c;造成任何后果自负与本人无关。 中华人民共和国网络安全法&#xff08;2017 年 6 月 1 日起施行&#xff09; 第二十二条 任何个人和组织不得从事入侵他人网络、干扰他…

折线图实现柱状阴影背景的demo

这个是一个由官网的基础折线图实现的流程&#xff0c;将涉及到的知识点附上个人浅薄的见解&#xff0c;源码在最后&#xff0c;需要的可自取。 折线图 成果展示代码注解参数backgroundColordataZoomlegendtitlexAxisyAxisgridseries 源码 成果展示 官网的基础折线图&#xff…

Android之Handler原理解析与问题分享

一、Handler运行原理剖析 1.关系剖析图 如果把整个Handler交互看做一个工厂&#xff0c;Thread就是动力MessageQueue是履带Looper是转轴Loooper的loop方法就是开关&#xff0c;当调用loop方法时整个工厂开始循环工作&#xff0c;处理来自send和post提交到MessageQueue的消息&a…

Nodejs 第四十五章(redis发布订阅+事务)

发布订阅 发布-订阅是一种消息传递模式&#xff0c;其中消息发布者&#xff08;发布者&#xff09;将消息发送到频道&#xff08;channel&#xff09;&#xff0c;而订阅者&#xff08;订阅者&#xff09;可以订阅一个或多个频道以接收消息。这种模式允许消息的解耦&#xff0…

006-CSS-常见问题汇总

常见问题汇总 1、伪元素与伪类2、偏门但好用的样式3、文字溢出三个点展示4、空白折叠问题5、文字的垂直居中6、 Vue项目中 在父组件中修改子组件样式7、BFC 概念7.1、兄弟元素外边距合并7.2、父子元素外边距塌陷 8、box-sizing8.1、box-sizing: border-box8.2、box-sizing: con…

11. Nginx进阶-HTTPS

简介 基本概述 SSL SSL是安全套接层。 主要用于认证用户和服务器&#xff0c;确保数据发送到正确的客户机和服务器上。 SSL可以加密数据&#xff0c;防止数据中途被窃取。 SSL也可以维护数据的完整性&#xff0c;确保数据在传输过程中不被改变。 HTTPS HTTPS就是基于SSL来…

1.1_2 性能指标——速率、带宽、吞吐量

文章目录 1.1_2 性能指标——速率、带宽、吞吐量&#xff08;一&#xff09;速率&#xff08;二&#xff09;带宽&#xff08;三&#xff09;吞吐量 1.1_2 性能指标——速率、带宽、吞吐量 &#xff08;一&#xff09;速率 速率即数据率或称数据传输率或比特率。 速率就是“快…

【代码】Python3|无GUI环境中使用Seaborn作图的学习路线及代码(阴影折线图)

我有个需求是需要画图&#xff0c;让GPT帮我生成了一下学习计划。 学习路线依照GPT的来的&#xff0c;使用的Prompt工具是https://github.com/JushBJJ/Mr.-Ranedeer-AI-Tutor。 文章目录 PrerequisiteMain Curriculum1.1 Seaborn介绍Seaborn基础保存图形为文件练习 1.2 单变量数…

瑞芯微RK3588 C++部署Yolov8检测和分割模型

最近这一个月在研究国产瑞芯微板子上部署yolov8的检测和分割模型&#xff0c;踩了很多坑&#xff0c;记录一下部署的过程和遇到的一些问题&#xff1a; 1 环境搭建 需要的环境和代码主要包括&#xff1a; &#xff08;1&#xff09;rknn-toolkit2-1.5.2&#xff1a;工具链&am…

uniapp开发android原生插件

一、下载原生开发SDK Android 离线SDK - 正式版 | uni小程序SDK (dcloud.net.cn)、 https://nativesupport.dcloud.net.cn/AppDocs/download/android.html 将开发uniappa原生android的插件解压到ben本地目录&#xff0c;目录结构如下&#xff1a; 接下就可以使用 UniPlugin-Hel…

12 状态优先级

概念 cpu需要执行很多进程&#xff0c;有很多进程排在队列中&#xff0c;每个进程加载后运行一定的时间段&#xff0c;然后切换下一个进程。cpu如何判断进程需不需要加载&#xff0c;什么时候加载&#xff0c;依靠进程的状态和优先级属性来判断&#xff0c;进程调度&#xff0…

Node.js与Webpack笔记(一)

这里使用的16.19.0版本&#xff0c;官网和github没找到&#xff0c;去黑马2023年课程里找 篇幅较大会卡&#xff0c;此篇幅不写Webpack部分&#xff0c;留着下一篇 初识 1.什么是Node.js? Node.js 是一个独立的 JavaScript 运行环境&#xff0c;能独立执行 JS 代码&#xff…

A/D转换

硬件电路模型 模数转换代码 main.c #include <REGX52.H> #include "LCD1602.h" #include "Delay.h" #include "XPT2046.h"unsigned int ADValue; int main(){LCD_Init();LCD_ShowString(1,1,"ADJ NTC RG");while(1){ADValue …

iOS 17.0 UIGraphicsBeginImageContextWithOptions 崩溃处理

在升级到iOS17后你会发现&#xff0c;之前版本运行的很好&#xff0c;这个版本突然会出现一个运行闪退。报错日志为*** Assertion failure in void _UIGraphicsBeginImageContextWithOptions(CGSize, BOOL, CGFloat, BOOL)(), UIGraphics.m:410 跟踪到具体的报错位置如下所示&a…

redis09 集群(cluster)

思维草图 为什么要使用集群 单台redis内存容量的限制单台redis并发写量太大有性能瓶颈 redis集群认识 redis集群是对redis的水平扩容&#xff0c;即启动N个redis节点&#xff0c;将整个数据分布存储在这个N个节点中&#xff0c;每个节点存储总数据的1/N。 如下图&#xff1…

win11部署自己的privateGpt(2024-0304)

什么是privateGpt? privategpt开源项目地址 https://github.com/imartinez/privateGPT/tree/main 官方文档 https://docs.privategpt.dev/overview/welcome/welcome PrivateGPT是一个可投入生产的人工智能项目&#xff0c;利用大型语言模型&#xff08;LLMs&#xff09;的…

Windows安装SSH教程

Windows安装SSH教程 一、SSH1.SSH简介2.SSH功能3.SSH验证3.1 第一种级别&#xff08;基于口令的安全验证&#xff09;3.2 第二种级别&#xff08;基于密匙的安全验证&#xff09; 4.SSH层次4.1 传输层协议 [SSH-TRANS]4.2 用户认证协议 [SSH-USERAUTH]4.3 连接协议 [SSH-CONNEC…

场景问题: VisualVM工具Profiler JDBC不是真实执行的SQL

1. 问题 诡异的问题表象&#xff1a; 前端反馈分页接口的Total字段一直为0 使用Visualvm中的 Profiler 注入到应用后&#xff0c;查看JDBC监控得到了分页接口执行的SQL&#xff0c;复制出来执行是55. 此时还没有注意到 IN 的范围中有一个特别的值 NULL &#x1f928; 2. 排查…

【运维必学】2.零基础搞IT运维之服务器操作系统基础知识储备

微信改版了&#xff0c;现在看到我们全凭缘分&#xff0c;为了不错过【全栈工程师修炼指南】重要内容及福利&#xff0c;大家记得按照上方步骤设置「接收文章推送」哦~ 文章目录&#xff1a; 温馨提示&#xff1a;作者最近开通的知识星球&#xff0c;全栈系列从门到实践教程将会…