[Springboot]安全框架Spring Security使用

news/2025/2/19 14:32:55/

一、介绍

Spring Security是一个基于Spring框架的安全性框架。
它提供了诸如认证、授权、攻击防御等功能,可以保护Web应用程序中的资源。

二、作用

认证(Authentication)

验证用户的身份。

授权(Authorization)

限制用户对应用程序的访问。


三、SpringBoot项目使用

1、maven依赖

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

引入后项目就能使用了。
未登录用户会自动跳转到Spring Security提供的登录页面。

  • 默认用户:user;
  • 默认密码:会在控制台打印Using generated security password: xxxxx 。

2、认证配置——实现 UserDetailsService 接口

登录不可能使用Spring Security默认配置,我们需要用自己的账户去登录。
如果我们需要进行以下配置。

@Service
public class MyUserDetailsService implements UserDetailsService {public static record MyUser(String username,String password){};public MyUser queryUserFromDB(String username){//todo 自定义从数据库查询用户数据//这里我定死了一个用户return new MyUser(username,"123456");}// 自定义认证逻辑@Overridepublic UserDetails loadUserByUsername(String username){// 1.查询用户MyUser user = queryUserFromDB(username);// 2.封装为UserDetails对象UserDetails userDetails = User.withUsername(user.username).password(user.password).authorities("admin").build();// 3.返回封装好的UserDetails对象return userDetails;}/*** 配置密码解析器* 假如数据库密码没加密,使用NoOpPasswordEncoder* 假如数据库密码有加密,使用NBCryptPasswordEncoder* @return*/@Beanpublic PasswordEncoder passwordEncoder(){return NoOpPasswordEncoder.getInstance();}
}

3、登录页面配置——继承 WebSecurityConfigurerAdapter 类

Spring Security提供了登录页面,但我们更多的是使用自己的登录页面。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{//Spring Security配置@Overrideprotected void configure(HttpSecurity http) throws Exception {// 自定义表单登录http.formLogin().loginPage("/login.html") //自定义登录页面.usernameParameter("username")// 表单中的用户名项.passwordParameter("password")// 表单中的密码项.loginProcessingUrl("/login") // 登录路径,表单向该路径提交,提交后自动执行UserDetailsService的方法.successForwardUrl("/index")//登录成功后跳转的路径.failureForwardUrl("/fail");//登录失败后跳转的路径// 配置需要认证的资源http.authorizeRequests().antMatchers("/login.html").permitAll() //登录页不需要认证.anyRequest().authenticated();//其余所有请求都需要认证//关闭csrf防护,默认开启了CSRF防护http.csrf().disable();}@Overridepublic void configure(WebSecurity web) throws Exception {// 静态资源放行web.ignoring().antMatchers("/css/**");web.ignoring().antMatchers("/js/**");web.ignoring().antMatchers("/img/**");}
}

4、如果登录成功/失败,需要额外处理。

登录成功——实现AuthenticationSuccessHandler 接口
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {@Overridepublic void onAuthenticationSuccess(HttpServletRequest
request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {// 拿到登录用户的信息UserDetails userDetails = (UserDetails)authentication.getPrincipal();//todo 自定义登录成功操作// 重定向到主页response.sendRedirect("/index");}
}

在SecurityConfig 配置 AuthenticationSuccessHandler

public class SecurityConfig extends WebSecurityConfigurerAdapter{//Spring Security配置@Overrideprotected void configure(HttpSecurity http) throws Exception {//http.successForwardUrl("/index")http.successHandler(new MyLoginSuccessHandler()) //登录成功处理器//定义successHandler后就不用设置successForwardUrl}
}
登录失败——实现AuthenticationFailureHandler 接口
public class MyLoginFailureHandler implements AuthenticationFailureHandler {@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {//todo 自定义失败操作response.sendRedirect("/fail");}
}

在SecurityConfig 配置 AuthenticationFailureHandler

public class SecurityConfig extends WebSecurityConfigurerAdapter{//Spring Security配置@Overrideprotected void configure(HttpSecurity http) throws Exception {//http.failureForwardUrl("/fail");http.failureHandler(new MyLoginFailureHandler());//定义failureHandler后就不用设置failureForwardUrl}
}

5、退出配置

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{//Spring Security配置@Overrideprotected void configure(HttpSecurity http) throws Exception {// 退出登录配置http.logout().logoutUrl("/logout") // 退出登录路径.logoutSuccessUrl("/login.html") // 退出登录后跳转的路径.clearAuthentication(true) //清除认证状态,默认为true.invalidateHttpSession(true); // 销毁HttpSession对象,默认为true}
}

6、Controller获取登录用户信息

@RestController
public class MyController {// 获取当前登录用户名@RequestMapping("/users/username")public String getUsername(){// 1.获取会话对象SecurityContext context = SecurityContextHolder.getContext();// 2.获取认证对象Authentication authentication = context.getAuthentication();// 3.获取登录用户信息UserDetails userDetails = (UserDetails) authentication.getPrincipal();return userDetails.getUsername();}
}

原文 : https://developer.aliyun.com/article/1135702


http://www.ppmy.cn/news/1156142.html

相关文章

java中转义字符的源码数据格式,内存存储数据格式和转换json后的数据格式

转义字符在内存存储格式 于 转换json后发送的数据格式是不一样的。因为json对于java来说可以看成一种源码&#xff0c;那就需要以源码的表示格式输出。 要注意转义字符在每种语言的源码的数据格式 和 内存存储的数据格式。 例&#xff1a;\n 换行转义字符 1.在java源码中为\…

无法解析符号 ‘SpringBootApplication’

刚打开一个项目出现"SpringBootApplication"无法解析&#xff1a; 通过以下步骤&#xff0c;修改maven路径即可&#xff1a; 文件---->设置&#xff08;File--->Settings&#xff09; 构建、执行、部署--->构建工具--->Maven--->Maven主路经&#xf…

设计模式再探——适配器模式

目录 一、背景介绍二、思路&方案三、过程1.适配器模式简介2.适配器模式的类图3.适配器模式代码4.适配器模式&#xff0c;类适配器模式和对象的对比5.适配器模式终极奥秘 四、总结五、升华 一、背景介绍 最近公司在对业务模型做构建的时候&#xff0c;涉及到和三方系统的对…

解决Drag and drop is not supported导致无法将物理机上的文件拖入Ubuntu

问题起因 因为需要拷贝一个文件从物理机到虚拟机&#xff0c;但是我又不想用有关ftp的程序或者协议&#xff0c;但是直接拖又报错Drag and drop is not supported&#xff0c;索性上网查询了一下解决方法&#xff0c;自己记录一下。 解决方法 安装下面两个程序 sudo apt in…

创意作品管理软件 Bridge 2024 mac中文版 br2024功能特色

Bridge 2024 mac旨在连接不同的Ad obe应用程序&#xff0c;帮助用户更轻松地管理和编辑他们的创意作品。 Bridge 2024 mac软件特色和功能介绍 一致的用户体验&#xff1a;Bridge 2024现在具有增强的用户界面&#xff0c;可提供与其他Creative Cloud应用程序类似的体验。用户还…

字符串思维题练习 DAY6 (CF 245H , CF 559B , CF 1731C , CF1109B)

字符串思维题练习 DAY6 (CF 245H , CF 559B , CF 1731C &#xff0c; CF1109B) CF 245 H. Queries for Number of Palindromes&#xff08;字符串 dp&#xff09; Problem - H - Codeforces 大意&#xff1a;给出一个字符串S (|S| ≤ 5000) , 给出 Q 次询问 &#xff0c; 每…

简单谈谈我参加计算机二级C语言的考试感受

简单谈谈我参加计算机二级C语言的考试感受 概要考试感受小结 概要 计算机二级c语言主要内容是熟练掌握C语言基础语法&#xff0c;了解常用数据结构和算法&#xff0c;能够使用C语言进行程序设计&#xff0c;编写简单的应用程序。 计算机二级C语言试卷类型&#xff1a; 选择题…

机器学习 | Python实现GA-XGBoost遗传算法优化极限梯度提升树特征分类模型调参

机器学习 | Python实现GA-XGBoost遗传算法优化极限梯度提升树特征分类 目录 机器学习 | Python实现GA-XGBoost遗传算法优化极限梯度提升树特征分类基本介绍模型描述程序设计参考资料基本介绍 XGBoost的核心算法思想基本就是: 不断地添加树,不断地进行特征分裂来生长一棵树,每…