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

Spring Security配置详细

Spring Security 使用教程

引言

Spring Security 是一个功能强大且高度可定制的身份验证和访问控制框架,专为基于Spring的应用程序设计。本教程将指导你如何在一个简单的Spring Boot应用程序中集成Spring Security,以实现基本的用户认证和授权功能。

环境准备

确保你已经安装了以下软件:

  • Java Development Kit (JDK) 1.8 或更高版本
  • Maven 或 Gradle(用于构建项目)
  • IDE(如 IntelliJ IDEA, Eclipse 或 Spring Tool Suite)

创建Spring Boot项目

  1. 使用Spring Initializr(https://start.spring.io/)

    • 选择你的项目元数据(如 Group, Artifact, Name, Description, Package name, Packaging, Java, Spring Boot 版本等)。
    • 添加 Spring WebSpring Security 依赖。
    • 生成项目并下载。
  2. 解压并导入到IDE中

    • 解压下载的项目文件。
    • 在你的IDE中导入这个Maven项目。

配置Spring Security

  1. 添加Security配置类
    src/main/java/com/example/demo/config(或你的包路径)下创建一个名为 SecurityConfig.java 的类。

    package com.example.demo.config;
    
    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 SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/", "/home").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");
        }
    }
    
  2. 创建Controller
    src/main/java/com/example/demo/controller 下创建一个名为 HomeController.java 的类。

    package com.example.demo.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    
    @Controller
    public class HomeController {
    
        @GetMapping("/")
        public String home() {
            return "redirect:/home";
        }
    
        @GetMapping("/home")
        public String homePage() {
            return "home";
        }
    
        @GetMapping("/login")
        public String loginPage() {
            return "login";
        }
    }
    
  3. 添加Thymeleaf模板
    src/main/resources/templates 下创建 home.htmllogin.html

    login.html 示例:

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Login</title>
    </head>
    <body>
        <h2>Login Page</h2>
        <form th:action="@{/login}" method="post">
            <div>
                <label> Username: </label>
                <input type="text" name="username"/>
            </div>
            <div>
                <label> Password: </label>
                <input type="password" name="password"/>
            </div>
            <div>
                <button type="submit">Sign In</button>
            </div>
        </form>
    </body>
    </html>
    

    home.html 示例:

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Home</title>
    </head>
    <body>
        <h1>Welcome Home!</h1>
    </body>
    </html>
    

运行和测试

  1. 运行你的Spring Boot应用
    在IDE中运行你的主应用类(通常带有 @SpringBootApplication 注解)。

  2. 访问应用

    • 在浏览器中访问 http://localhost:8080/,你应该会被重定向到登录页面。
    • 使用用户名 user 和密码 password 登录。
    • 登录成功后,你应该能看到欢迎页面。

结论

通过以上步骤,你已经成功地在Spring Boot应用中集成了Spring Security,并实现了基本的用户认证和授权功能。你可以根据需要进一步扩展和定制安全配置,如连接数据库进行用户认证、实现更复杂的权限控制等。

当然可以,下面是对您提供的SecurityConfig类中的每一行代码的详细解释:

package com.example.demo.config;
  • 这行指定了当前类所在的包路径。
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;
  • 这些行导入了Spring Security配置所需的类和接口。@Configuration用于标识这是一个配置类,EnableWebSecurity用于启用Web安全配置,WebSecurityConfigurerAdapter是一个适配器类,提供了配置Web安全性的方法。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  • @Configuration注解表明这个类是一个配置类。
  • @EnableWebSecurity注解用于启用Spring Security的Web安全功能。
  • public class SecurityConfig extends WebSecurityConfigurerAdapter定义了一个名为SecurityConfig的公开类,该类继承自WebSecurityConfigurerAdapter,以便能够重写其方法来配置Web安全。
    @Override
    protected void configure(HttpSecurity http) throws Exception {
  • 这个方法用于配置HTTP安全。通过重写WebSecurityConfigurerAdapter中的configure(HttpSecurity http)方法,可以定义哪些URL模式需要被保护,以及如何保护它们。
        http  
            .authorizeRequests()  
                .antMatchers("/", "/home").permitAll() // 允许所有人访问  
                .anyRequest().authenticated() // 其他请求都需要认证  
                .and()  
  • 这部分配置定义了哪些URL模式应该被授权访问。antMatchers("/", "/home").permitAll()表示允许所有人访问根URL(/)和/home路径。anyRequest().authenticated()表示所有其他请求都需要用户认证。
            .formLogin() // 使用表单登录  
                .loginPage("/login") // 指定登录页面  
                .permitAll() // 允许所有人访问登录页面  
                .and()  
  • 这部分配置启用了表单登录,并指定了登录页面的URL为/loginpermitAll()表示允许所有人访问登录页面,无需认证。
            .logout() // 登出配置  
                .permitAll(); // 允许所有人访问登出功能  
    }
  • 这部分配置定义了登出行为。permitAll()表示允许所有人访问登出功能,即无需认证即可执行登出操作。
    // 这里可以配置内存中的用户,实际开发中通常会连接数据库  
    @Override  
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {  
        auth  
            .inMemoryAuthentication()  
            .withUser("user").password("{noop}password").roles("USER");  
    }
  • 这个方法用于配置认证管理器。在这个例子中,它配置了内存中的用户认证。inMemoryAuthentication()表示使用内存中的用户存储进行认证。withUser("user").password("{noop}password").roles("USER")定义了一个用户名为user,密码为password(注意这里使用了{noop}前缀,表示不对密码进行编码,实际开发中应避免这样做),并赋予其USER角色的用户。在实际应用中,通常会连接数据库来管理用户信息。

http://www.kler.cn/news/283340.html

相关文章:

  • 力扣: 环形链表
  • NFT Insider #144:Sandbox 投资 9 万美元助力区块链活动
  • LABVIEW数据保存文件
  • MVC与设计模式理解-lnmp学习之路
  • linux配置jenkins环境
  • 深入理解 SQL 注入漏洞原理
  • ROS机器人专用云台相机防抖摄像头
  • Redis 常用命令
  • 上门解民忧 中信银行太原分行适老化金融服务提升温度
  • 【产品那些事】什么是软件成分分析(SCA)?
  • 【赵渝强老师】Redis的管道Pipeline
  • 【Linux】用户和用户组管理(第四篇)
  • 山东省大数据职称考试(2)
  • K13021 - 小科坐地铁
  • GAN:数据生成的魔术师
  • 查看 linux 系统信息
  • MySQL——多表操作(四)(2)带 EXISTS 关键字的子查询
  • ruoyi-app前端在缓存中添加nick_name和user_id属性值
  • windows安装macos虚拟机
  • apisix 本地开发环境部署
  • iOS/iPadOS18.1Beta3发布,新增通知摘要和AI消除功能
  • 如何在CenOS7上安装docker
  • PostgreSQL:后端开发者的瑞士军刀
  • 给自己复盘用的tjxt笔记day12第一部分
  • 【原型设计工具评测】Axure、Figma、Sketch三强争霸
  • 关于stm32的硬件CRC32与U盘分区中的CRC32计算方式不同的探索;stm32的硬件CRC32的使用细节;stm32的硬件CRC32的问题;
  • gin 通过 OpenTelemetry 实现链路追踪
  • 上新!Matlab实现基于QRGRU-Attention分位数回归门控循环单元注意力机制的时间序列区间预测模型
  • 数学基础 -- 线性代数之增广矩阵
  • Redis缓存穿透、缓存击穿与缓存雪崩的详细讲解和案例示范