详解 Spring Security:全面保护 Java 应用程序的安全框架

详解 Spring Security:全面保护 Java 应用程序的安全框架

Spring Security 是一个功能强大且高度可定制的框架,用于保护基于 Java 的应用程序。它为身份验证、授权、防止跨站点请求伪造 (CSRF) 等安全需求提供了解决方案。下面将更详细地介绍 Spring Security 的各个方面:
CSDN开发云

1. 核心概念

1.1 身份验证 (Authentication)

身份验证是确认用户身份的过程。Spring Security 提供了多种身份验证机制,如表单登录、HTTP Basic、OAuth2 等。

  • AuthenticationManager:用于管理认证过程的核心接口,通常通过ProviderManager 实现。
  • Authentication:表示认证请求或认证结果的接口,通常包含用户名和密码等信息。
  • UserDetailsService:用于从数据库或其他源加载用户特定数据的接口,返回 UserDetails 对象。
  • UserDetails:存储用户信息的核心接口,通常包含用户名、密码、是否启用、账户是否过期、凭证是否过期、账户是否锁定等信息。

1.2 授权 (Authorization)

授权是控制用户访问资源的过程。Spring Security 使用基于角色的访问控制 (RBAC) 和权限来实现授权。

  • AccessDecisionManager:用于做出访问决策的核心接口,通常通过 AffirmativeBased 实现。
  • AccessDecisionVoter:投票决定是否允许访问,ROLE、Scope 和 IP 是常见的投票者类型。
  • GrantedAuthority:表示授予用户的权限(例如角色)的接口,通常通过 SimpleGrantedAuthority 实现。

1.3 过滤器链 (Filter Chain)

Spring Security 使用一系列过滤器(Filter Chain)来处理安全相关的操作。每个过滤器在请求到达控制器之前进行特定的安全检查。

  • SecurityFilterChain:包含一个或多个过滤器的链,按顺序处理 HTTP 请求。

2. 核心组件

2.1 SecurityContext

用于保存当前已认证用户的安全上下文信息,通常通过 SecurityContextHolder 来访问。

  • SecurityContextHolder:持有当前应用程序的安全上下文信息,允许获取当前用户的身份信息。

    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    String username = authentication.getName();
    

2.2 HttpSecurity

用于配置基于 HTTP 的安全保护,包括设置哪些 URL 需要保护、使用哪种认证方式等。

http
    .authorizeRequests()
        .antMatchers("/public/**").permitAll()
        .anyRequest().authenticated()
    .and()
    .formLogin()
        .loginPage("/login")
        .permitAll()
    .and()
    .logout()
        .permitAll();

2.3 WebSecurityConfigurerAdapter

一个配置类,用于自定义 Spring Security 的配置,通常通过重写 configure 方法来设置各种安全选项。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
            .and()
            .logout()
                .permitAll();
    }

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

3. 认证机制

3.1 基于表单的认证 (Form-Based Authentication)

用户通过登录表单提交用户名和密码进行认证。

http
    .formLogin()
        .loginPage("/login")
        .loginProcessingUrl("/perform_login")
        .defaultSuccessUrl("/homepage.html", true)
        .failureUrl("/login.html?error=true")
        .and()
    .logout()
        .logoutUrl("/perform_logout")
        .deleteCookies("JSESSIONID");

3.2 HTTP Basic 认证

使用 HTTP Basic 头信息进行认证。

http
    .authorizeRequests()
        .anyRequest().authenticated()
    .and()
    .httpBasic();

3.3 Token-Based 认证 (如 JWT)

使用令牌(如 JWT)在客户端和服务器端之间传递身份认证信息。

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        // 从请求中提取用户名和密码
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        // 生成 JWT 并在响应中返回
    }
}

4. 授权机制

4.1 基于 URL 的授权

通过配置哪些 URL 需要哪些角色或权限来进行授权。

http
    .authorizeRequests()
    .antMatchers("/admin/**").hasRole("ADMIN")
    .antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
    .anyRequest().authenticated();

4.2 基于方法的授权

通过注解方式,在方法级别上进行授权。

@PreAuthorize("hasRole('ROLE_USER')")
public void someMethod() {
    // Method implementation
}

5. 防护措施

5.1 CSRF (Cross-Site Request Forgery)

Spring Security 默认启用 CSRF 防护,保护应用免受 CSRF 攻击。

http
    .csrf().disable();  // 禁用 CSRF 防护(不推荐)

5.2 CORS (Cross-Origin Resource Sharing)

配置跨域资源共享策略,允许或限制跨域请求。

http
    .cors().configurationSource(corsConfigurationSource());

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

6. 集成 OAuth2

Spring Security 提供了对 OAuth2 和 OpenID Connect 的支持,可以轻松集成第三方身份提供者(如 Google、Facebook)。

@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(a -> a
                .anyRequest().authenticated()
            )
            .oauth2Login();
    }
}

7. 自定义扩展

7.1 自定义 UserDetailsService

通过实现 UserDetailsService 接口来自定义用户数据的加载逻辑。

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 自定义用户加载逻辑
        return new User(username, password, authorities);
    }
}

7.2 自定义认证过滤器

通过扩展 UsernamePasswordAuthenticationFilter 来实现自定义的认证逻辑。

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
        // 自定义认证逻辑
    }
}

8. 配置示例

以下是一个完整的 Spring Security 配置示例,结合了以上讲述的各个方面:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/perform_login")
                .defaultSuccessUrl("/homepage.html", true)
                .failureUrl("/login.html?error=true")
                .permitAll()
            .and()
            .logout()
                .logoutUrl("/perform_logout")
                .deleteCookies("JSESSIONID")
                .permitAll()
            .and()
            .csrf().disable()
            .cors().configurationSource(corsConfigurationSource());
    }

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

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

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

总结

Spring Security 提供了全面的安全功能,几乎可以满足所有 Java 应用程序的安全需求。通过配置和自定义,可以灵活地实现身份验证和授权逻辑,并保护应用免受各种安全威胁。掌握 Spring Security 的核心概念和组件,有助于开发人员构建安全可靠的应用程序。

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

ComfyUI

文章目录 一、关于 ComfyUI特点快捷键QA你为什么做这个?这是给谁的? 二、安装1、Windows直接链接下载如何在另一个UI和ComfyUI之间共享模型? 2、Jupyter Notebook3、手动安装(Windows、Linux)AMD GPU(仅Lin…

2024年黑龙江省特岗招聘公告出了!!!

2024年黑龙江省农村义务教育阶段学校特设岗位教师招聘822人公告 (1、网上报名 时间:6月17日9:00—6月22日17:00。 网址: https://sfyz.hljea.org.cn:7006/tgjs 2、网上资格审查 资格审查时间:6月…

时间卷积网络与膨胀卷积:深入理解其原理与应用

TCN, Temporal Convolutional Networks 时间卷积网络与膨胀卷积:深入理解其原理与应用一、时间卷积网络(TCN)简介二、膨胀卷积的核心概念1. **膨胀卷积(Dilated Convolution)**2. **Kernel(卷积核&#xff…

js 前端 Function.prototype.call.call(0[‘toString‘], *, 16)

这个函数将 数组转任意进制 Function.prototype.call.call(0[toString], *, 16)

计算机组成原理之定点运算器的组成

文章目录 定点运算器的组成逻辑运算ALU两级先行进位的ALU 总线单总线结构双总线结构三总线结构 定点运算器的组成 逻辑运算 总的来说,逻辑非运算就是按位取反;逻辑加运算就是按位取或运算;逻辑乘运算就是按位取和运算;逻辑异运算…

2-6 基于matlab2018B的语音信号降噪和盲源分离GUI界面

基于matlab2018B的语音信号降噪和盲源分离GUI界面,包括维纳滤波,小波降噪、高通、低通、带通滤波,及提出的滤波方法。每个功能均展示降噪前后声音效果并外放出来。程序已调通,可直接运行。 2-6 语音信号降噪 盲源分离 GUI界面 - 小…

UML相关2

内容 说明 用例编号 UC-1 用例名称 客户注册 用例说明 客户参与者通过注册获得进入彬使用系统的权限 参与者 客户 前置条件 无 后置条件 系统正确接收用户信息并保存到数据库 基本路径 发布注册申请系统显示注册页面客户填写相应信息并提交注册成功后可以进行其…

贷款投资决策和常用财务函数

前段时间上了一门excel操作的课,本文结合其中介绍财务函数以及投资决策分析相关的部分,对贷款中的现金流计算进行深入的分析。 以等额本息产品为例进行实操计算,假设某产品本金12000元,期限12,IRR利率24%。每期还款113…

生信分析进阶5 - 全外显子组变异检测和ANNOVAR注释Snakemake分析流程

基于yaml或ini配置文件,配置文件包含例如样本名称、参考基因组版本、exon capture bed文件路径、参考基因组路径和ANNOVAR注释文件等信息。 基于该流程可以实现全外显测序的fastq文件输入到得到最终变异VCF文件。 1. Snakemake分析流程基础软件安装 # conda安装 …

面试题 17.17. 多次搜索

链接&#xff1a;. - 力扣&#xff08;LeetCode&#xff09; 题解&#xff1a; class Solution { private:struct Trie {Trie() {end false;index -1;next.resize(26);}bool end;int index;std::vector<std::unique_ptr<Trie>> next;};void insert_trie(int in…

C++编程:vector容器的简单模拟实现

前言&#xff1a; 在C标准库&#xff08;STL&#xff09;中&#xff0c;vector容器是最常见使用的动态数组。它结合了链表与数组的优点&#xff0c;提供了灵活的大小调整与高效的随机访问。本文将简单的对vector容器进行介绍并且对vector容器简单的模拟实现。 一、vector的文…

web前端:作业三

1.回到顶部案例(固定定位) <!DOCTYPE html> <html><head><meta charset"utf-8"><title></title><style>#container{height: 5000px;border: 1px solid blue;}#back-button{width: 100px;height: 100px;border: 1px solid…

Redis分布式锁的实现、优化与Redlock算法探讨

Redis分布式锁最简单的实现 要实现分布式锁,首先需要Redis具备“互斥”能力,这可以通过SETNX命令实现。SETNX表示SET if Not Exists,即如果key不存在,才会设置它的值,否则什么也不做。利用这一点,不同客户端就能实现互斥,从而实现一个分布式锁。 举例: 客户端1申请加…

比亚迪智驾技术震撼登场!L3级自动驾驶领跑全国,无图导航、夜间挑战轻松应对!

作为新能源汽车领域的翘楚&#xff0c;比亚迪在电池技术与智能驾驶方面都有着卓越的表现。近日&#xff0c;比亚迪凭借其领先的智驾技术&#xff0c;成功入选全国首批L3级自动驾驶上路及行驶试点名单&#xff0c;这无疑将推动智驾技术的普及速度。 你知道吗&#xff1f;比亚迪智…

Elasticsearch 认证模拟题 - 22

一、题目 索引 task 索引中文档的 fielda 字段内容包括了 hello & world&#xff0c;索引后&#xff0c;要求使用 match_phrase query 查询 hello & world 或者 hello and world 都能匹配该文档 1.1 考点 分词器 1.2 答案 # 创建符合条件的 task 索引&#xff0c;…

SM2加密算法的公私钥和密文格式以及不同编程语言之间无法互相解密问题分析

1 文章介绍 本文章主要介绍了SM2加密算法的公钥、私钥和密文格式,以及对于不同编程语言之间无法互相解密问题进行了分析和处理。2 SM2加密算法格式 SM2在线加解密测试2.1 公钥格式 SM2公钥是SM2曲线上的一个点,由横、纵坐标两个分量来表示,简记为Q,每个分量长度为256位,即…

Apipost模拟HTTP客户端

模拟HTTP客户端的软件有很多&#xff0c;其中比较著名的就有API-FOX、POSTMAN。 相信很多小伙伴都使用POSTMAN。这篇博客主要介绍Apipost的原因是&#xff0c;Apipost无需下载&#xff0c;具有网页版。 APIFOX的站内下载&#xff1a; Api-Fox&#xff0c;类似于PostMan的软件…

[力扣二叉树]本地调试环境指导手册

以236. 二叉树的最近公共祖先为例子 本地编译软件为Viusal Studio 2022 写代码 项目里文件位置 CreateTree.h #pragma once #ifndef CLIONPROJECT_LEETCODECREATETREE_H #define CLIONPROJECT_LEETCODECREATETREE_H #include<vector> #include<queue> using na…

Java语法和基本结构介绍

Java语法和基本结构是Java编程的基础&#xff0c;它决定了Java代码的书写方式和程序的结构。以下是Java语法和基本结构的一些关键点&#xff1a; 1.标识符和关键字&#xff1a;Java中的标识符是用来标识变量、函数、类或其他用户自定义元素的名称。关键字是预留的标识符&#x…

【Netty】ByteBuffer原理与使用

Buffer则用来缓冲读写数据&#xff0c;常见的buffer有&#xff1a; ByteBuffer MappedByBuffer DirectByteBuffer HeapByteBuffer hortBuffer IntBuffer LongBuffer FloatBuffer DoubleBuffer CharBuffer 有一个普通文本文件data.txt,内容为&#xff1a; 1234567890a…