Spring Security基础使用

一、前言

Spring Security是一款基于Spring的安全框架,主要包含认证和授权两大安全模块,和另外一款流行的安全框架Apache Shiro相比,它拥有更为强大的功能。Spring Security也可以轻松的自定义扩展以满足各种需求,并且对常见的Web安全攻击提供了防护支持。如果你的Web框架选择的是Spring,那么在安全方面Spring Security会是一个不错的选择。

二、开启Spring Security

这里我们使用Spring Boot来集成Spring Security。

2.1 引入依赖

创建一个Spring Boot项目,然后引入spring-boot-starter-security:

xml 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

2.2 测试

接下来我们创建一个TestController,对外提供一个/hello服务

java 复制代码
@RestController
public class TestController {
    @GetMapping("hello")
    public String hello() {
        return "hello spring security";
    }
}

这时候我们直接启动项目,访问http://localhost:8080/hello,可看到HTTP Basic认证:

当Spring项目中引入了Spring Security依赖的时候,项目会默认开启如下配置:

yml 复制代码
security:
  basic:
    enabled: true

这个配置开启了一个HTTP basic类型的认证,所有服务的访问都必须先过这个认证,默认的用户名为user,密码由Sping Security自动生成,回到IDE的控制台,可以找到密码信息:

输入用户名user,密码744294ad-5717-4f0b-8932-d26d2e455711后,我们便可以成功访问/hello接口。

三、基于HTTP Basic认证

我们可以通过一些配置将基于表单认证修改为HTTP Basic的认证方式。

创建一个配置类BrowserSecurityConfig继承org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter这个抽象类并重写configure(HttpSecurity http)方法。WebSecurityConfigurerAdapter是由Spring Security提供的Web应用安全配置的适配器:

java 复制代码
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //http.formLogin() // 表单方式
        http.httpBasic() // HTTP Basic方式
                .and()
                .authorizeRequests() // 授权配置
                .anyRequest()  // 所有请求
                .authenticated(); // 都需要认证
    }
}

Spring Security提供了这种链式的方法调用。上面配置指定了认证方式为表单登录,并且所有请求都需要进行认证。这时候我们重启项目,再次访问Mhttp://localhost:8080/hello>,可以看到认证方式已经是HTTP Basic的方式了:

相关推荐
独泪了无痕20 小时前
Spring Data Redis 快速上手
spring boot·redis·后端
wangchunyu1141 天前
JAVA CompletableFuture异步编程实战
java·开发语言·python
paopaokaka_luck1 天前
流浪动物救助与收养系统(DeepSeek AI对话、 ECharts多维分析、救助流程衔接、领养与回访衔接、 捐赠确认与公示、志愿者协作)
java·前端·javascript·人工智能·mysql·echarts·推荐算法
Thomas.Sir1 天前
第9课:SpringBoot4.x Web开发基础:WebMvc自动配置、静态资源、请求参数接收
java·spring boot
程序 代码狂人1 天前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
m0_639906941 天前
Linux 操作系统入门:目录结构、服务排查常用命令、Shell 脚本基础
linux·运维·后端
2501_944521591 天前
Deepmerge 跨端三方库仓颉适配全流程
java·python·eclipse·github
holly就是我1 天前
AI 编程助手为什么跑偏?用开源 ccglass 看清 Prompt、工具调用和 Token 消耗
人工智能·后端
鸿蒙开发1 天前
共享 Schema 与 SchemaFactory
前端·后端·harmonyos
用户788477316341 天前
小程序后端三选一:云开发、.NET WebAPI、Node,我按客户现状分了三种答案
后端