基本认证概述
基本认证(Basic Auth)是保护REST API最简单的方式之一。它通过在HTTP请求头中携带Base64编码过的用户名和密码来进行身份验证。由于基本认证不使用cookie,因此没有会话或用户登出的概念,这意味着每次请求都必须包含身份验证信息。
Maven依赖
要在Spring Boot项目中使用Spring Security,需要添加以下Maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Security配置
接下来,我们将配置Spring Security以使用内存中的基本认证。创建一个名为SpringSecurityConfig
的类,并加入如下代码:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;