当前位置: 首页 > news >正文

Spring Security 使用教程

Spring Security 使用教程

Spring Security 是 Spring 提供的强大安全框架,主要用于认证(Authentication)与授权(Authorization)。本教程将从零开始,介绍如何使用 Spring Security 实现基本的安全控制。


一、Spring Security 基础概念

  • 认证(Authentication):验证用户身份是否合法。
  • 授权(Authorization):验证用户是否有权限访问资源。
  • 过滤器链(FilterChain):Spring Security 利用一系列过滤器实现安全逻辑。

二、快速开始

1. 添加依赖

pom.xml 中引入:

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

三、默认登录功能体验

添加依赖后,访问任意接口时会自动跳转到登录页面,默认用户名为 user,密码在控制台中输出。


四、自定义用户与密码

application.yml 中配置:

spring:
  security:
    user:
      name: admin
      password: 123456

五、自定义 Security 配置类

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()  // 允许访问的路径
                .anyRequest().authenticated()
            )
            .formLogin(Customizer.withDefaults())
            .logout(logout -> logout.permitAll());

        return http.build();
    }
}

六、自定义用户认证逻辑

1. 自定义 UserDetailsService

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if ("admin".equals(username)) {
            return User.builder()
                    .username("admin")
                    .password(new BCryptPasswordEncoder().encode("123456"))
                    .roles("USER")
                    .build();
        }
        throw new UsernameNotFoundException("用户不存在");
    }
}

2. 注入 UserDetailsService 到配置类

@Bean
public AuthenticationManager authenticationManager(HttpSecurity http, CustomUserDetailsService userDetailsService) throws Exception {
    return http.getSharedObject(AuthenticationManagerBuilder.class)
            .userDetailsService(userDetailsService)
            .passwordEncoder(new BCryptPasswordEncoder())
            .and()
            .build();
}

七、常用配置说明

配置说明
permitAll()所有人可访问
authenticated()登录用户可访问
hasRole("ADMIN")拥有角色 ADMIN 才能访问
formLogin()启用表单登录
httpBasic()启用 HTTP Basic 登录
csrf().disable()关闭 CSRF 保护(开发环境)

八、整合前后端分离项目

配置跨域和关闭默认登录页面:

http
    .csrf().disable()
    .cors(Customizer.withDefaults())
    .formLogin().disable();

在前端登录时使用 /login 接口 + JSON 请求体 + UsernamePasswordAuthenticationFilter

也可以自定义登录接口,手动调用 AuthenticationManager.authenticate() 完成认证。


九、总结

Spring Security 提供了完善的安全体系,可灵活配置认证与授权。通过简单的配置,就能快速构建一个安全的 Web 应用。

推荐结合 OAuth2、JWT、RBAC 等深入实践,提高安全策略的精细化程度。

如需了解更多,可参考官网文档:https://docs.spring.io/spring-security/

相关文章:

  • 三维激光测量助力企业检测效率提升3倍
  • 15.【.NET 8 实战--孢子记账--从单体到微服务--转向微服务】--单体转微服务--如何拆分单体
  • 状态机 XState
  • WiFi那些事儿(四)
  • 嵌入式Linux——8 串口
  • pytorch查询字典、列表维度
  • 应急响应排查系统技术解析
  • Ingress蓝绿发布
  • Redis 特性和应用场景
  • 测试模板1
  • python高级编程一(生成器与高级编程)
  • arcpy基础之环境搭建
  • 【QT】学习笔记1
  • leetcode刷题日记——赎金信
  • 【PyTorch项目实战】反卷积(Deconvolution)
  • 解决 weditor 报错AttributeError: ‘Device‘ object has no attribute ‘address’
  • Java对象内存结构详解
  • 文献总结:AAAI2025-UniV2X-End-to-end autonomous driving through V2X cooperation
  • linux RCU技术
  • Android11车载WiFi热点默认名称及密码配置
  • 网站在别人那里已经建好了_公司里要进行修改_怎么做/百度网址大全网站
  • 制作网页怎样添加背景音乐/优化seo公司哪家好
  • 建设网站内容的策划书/seo外链收录
  • 临朐营销型网站建设/软文推广策划方案
  • 昆明网站建设培训/河南网站公司
  • 建设网站需要什么人员/google chrome