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

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 {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/", "/home").permitAll() // 允许所有人访问.anyRequest().authenticated() // 其他请求都需要认证.and().formLogin() // 使用表单登录.loginPage("/login") // 指定登录页面.permitAll() // 允许所有人访问登录页面.and().logout() // 登出配置.permitAll(); // 允许所有人访问登出功能}// 这里可以配置内存中的用户,实际开发中通常会连接数据库@Overrideprotected 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,并实现了基本的用户认证和授权功能。你可以根据需要进一步扩展和定制安全配置,如连接数据库进行用户认证、实现更复杂的权限控制等。


http://www.mrgr.cn/news/15082.html

相关文章:

  • 固态硬盘损坏,有什么方法可以恢复数据?
  • 【算法进阶2-动态规划】斐波那契数列(递归调用、动态规划)、钢条切割问题(自定而下实现、自底向上、切割方案)
  • echo ‘‘ >>/etc/profile是什么意思什么效果
  • 信息安全--网络安全体系与安全模型
  • 8.29T2 国际象棋(构造:棋盘拆分成小方阵)
  • Linux sentinel写法
  • Day4 平衡树 线段树
  • Python 如何进行密码学操作(cryptography模块)
  • 数学基础 -- 线性代数之矩阵的秩
  • 云计算基础之Docker
  • linux-centos7 服务器上redis服务已经启动,但是宿主机无法访问,报错:connect timeout
  • Java Excel转PDF(免费)
  • Java Web —— 第九天(事务)
  • 样式(1)——颜色样式
  • 算法的学习笔记—从 1 到 n 整数中 1 出现的次数(牛客JZ43)
  • 【Qt窗口】—— 状态栏
  • 观测云「可观测性解决方案」亮相 828 B2B 企业节
  • 《多模态大规模语言模型基准》综述
  • react.js
  • [M模拟] lc3153. 所有数对中数位不同之和(模拟+按位统计)