Spring Security 弃用 WebSecurityConfigurerAdapter 重写登录接口

news/2024/6/23 18:17:15

springboot 版本高于 2.7 之后 弃用了 WebSecurityConfigurerAdapter  推荐使用组件化配置安全组件。

原版本的2.7版本的登录接口  

功能: 通过/api/doLogin 进行登录 

package cn.devops.config;import cn.devops.model.User;
import cn.devops.response.RespBean;
import cn.devops.service.DevopsService;
import cn.devops.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;/*** @author morey* 用户登录模块*/
@Configuration
public class SecurityConfig_bak extends WebSecurityConfigurerAdapter {@ResourceUserService userService;@ResourceDevopsService devopsService;/*** 带salt的加密*/@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder(5);}/*** 全局身份认证器*/@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userService);}/*** 配置需要忽略的url*/@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/fonts/**", "/js/**", "/css/**", "index.html", "favicon.ico", "/static/**", "/sys/**", "/user/**", "/actuator/**","/api/hello/admin");}/*** 配置具体的控制权限 http请求的安全处理* 配合拦截规则,表单登录,登录成功与失败的响应等*/@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests()//.antMatchers("/","index.html").permitAll().anyRequest().authenticated().and().formLogin().usernameParameter("username").passwordParameter("password").loginProcessingUrl("/api/doLogin")//.loginPage("/index.html").successHandler(new AuthenticationSuccessHandler() {@Overridepublic void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth)throws IOException, ServletException {resp.setContentType("application/json;charset=utf-8");//创建输出流,得到request文件流PrintWriter out = resp.getWriter();//Principal是一个包含用户标识和用户角色的对象User user = (User) auth.getPrincipal();//返回json时忽略password字段给前端 安全考虑user.setPassword(null);RespBean ok = RespBean.ok("登录成功", user);//将java对象转换成json字符串String s = new ObjectMapper().writeValueAsString(ok);//将request文件流写入json中out.write(s);out.flush();out.close();}}).failureHandler(new AuthenticationFailureHandler() {@Overridepublic void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {resp.setContentType("application/json;charset=utf-8");//获取响应流PrintWriter out = resp.getWriter();RespBean respBean = RespBean.error("登录失败");if (exception instanceof LockedException) {respBean.setMsg("账号锁定,请联系管理员");} else if (exception instanceof CredentialsExpiredException) {respBean.setMsg("密码过期,请联系管理员");} else if (exception instanceof AccountExpiredException) {respBean.setMsg("账号过期,请联系管理员");} else if (exception instanceof DisabledException) {respBean.setMsg("账号被禁用,请联系管理员");} else if (exception instanceof BadCredentialsException) {respBean.setMsg("用户名或密码错误,请重新输入");}out.write(new ObjectMapper().writeValueAsString(respBean));out.flush();out.close();}}).permitAll().and().logout().logoutSuccessHandler(new LogoutSuccessHandler() {@Overridepublic void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {resp.setContentType("application/json;charset=utf-8");PrintWriter out = resp.getWriter();out.write(new ObjectMapper().writeValueAsString(RespBean.ok("注销成功")));out.flush();out.close();}}).permitAll().and().csrf().disable();}
}

spring-boot-starter Security  3.2.2版本的写法


https://www.xjx100.cn/news/3271170.html

相关文章

Ubuntu Desktop - Files Preferences

Ubuntu Desktop - Files Preferences 1. Behavior2. ViewsReferences 1. Behavior Go to file browser’s Menu -> Edit -> Preferences -> Behavior 2. Views Go to file browser’s Menu -> Edit -> Preferences -> Views ​​​ References [1] Yong…

鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之LoadingProgress组件

鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之LoadingProgress组件 一、操作环境 操作系统: Windows 10 专业版、IDE:DevEco Studio 3.1、SDK:HarmonyOS 3.1 二、LoadingProgress组件 用于显示加载动效的组件。 子组件 无 接口 L…

【ES】--Elasticsearch的分词器深度研究

目录 一、问题描述及分析二、analyze分析器原理三、 multi-fields字段支持多场景搜索(如同时简繁体、拼音等)1、ts_match_analyzer配置分词2、ts_match_all_analyzer配置分词3、ts_match_1_analyzer配置分词4、ts_match_2_analyzer配置分词5、ts_match_3_analyzer配置分词6、ts…

AI:126-基于深度学习的人体情绪识别与分析

🚀点击这里跳转到本专栏,可查阅专栏顶置最新的指南宝典~ 🎉🎊🎉 你的技术旅程将在这里启航! 从基础到实践,深入学习。无论你是初学者还是经验丰富的老手,对于本专栏案例和项目实践都有参考学习意义。 ✨✨✨ 每一个案例都附带有在本地跑过的关键代码,详细讲解供…

Proteus -模拟串口被关闭后怎样打开

Proteus -模拟串口被关闭后怎样打开 点击恢复弹出窗口,即可重新打开

【C/C++ 16】C++11线程库

目录 一、thread类概述 二、多线程 三、原子性操作库 四、lock_guard 五、unique_guard 一、thread类概述 进程是操作系统进行资源调度的最小单位,线程是CPU进行任务执行的最小单位。 在C11之前,涉及到多线程问题,都是和平台相关的&am…

RK3588平台开发系列讲解(视频篇)RKMedia 数据流向

文章目录 一、 获取RKMedia模块通道中的数据二、RKMedia的数据源和接收者三、模块通道绑定API调用 沉淀、分享、成长,让自己和他人都能有所收获!😄 📢RKMedia是RK提供的一种多媒体处理方案,可实现音视频捕获、音视频输…

数据结构哈希表

这里个大家用数组来模拟哈希表 法一&#xff1a;拉链法 法二&#xff1a;开放寻址法 /** Project: 11_哈希表* File Created:Sunday, January 17th 2021, 2:11:23 pm* Author: Bug-Free* Problem:AcWing 840. 模拟散列表 拉链法*/ #include <cstring> #include <iostr…