Java17 --- SpringSecurity之前后端分离处理

目录

一、实现前后端分离

1.1、导入pom依赖

1.2、认证成功处理

1.3、认证失败处理

1.4、用户注销处理 

1.5、请求未认证处理 

1.6、跨域处理 

1.7、用户认证信息处理 

1.8、会话并发处理 

 


一、实现前后端分离

1.1、导入pom依赖

<dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId><version>2.0.40</version></dependency>

1.2、认证成功处理

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {//获取用户身份信息Object principal = authentication.getPrincipal();HashMap map = new HashMap<>();map.put("code",200);map.put("message","登录成功");map.put("data",principal);//将信息json化String jsonString = JSON.toJSONString(map);//返回json数据到前端response.setContentType("application/json;charset=UTF-8");response.getWriter().println(jsonString);}
}
@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {httpSecurity.authorizeRequests(authorize -> authorize.anyRequest() //对所有请求开启授权保护.authenticated() //已认证的请求会自动授权).formLogin(//Customizer.withDefaults()form -> form.loginPage("/login").permitAll()//无需授权就能访问.usernameParameter("name").passwordParameter("pass").successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理);//使用表单授权方式//.httpBasic(Customizer.withDefaults());//使用基本授权方式httpSecurity.csrf(csrf -> csrf.disable());//关闭csrf功能return httpSecurity.build();}

1.3、认证失败处理

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {String localizedMessage = exception.getLocalizedMessage();HashMap map = new HashMap<>();map.put("code",400);map.put("message",localizedMessage);//将信息json化String jsonString = JSON.toJSONString(map);//返回json数据到前端response.setContentType("application/json;charset=UTF-8");response.getWriter().println(jsonString);}
}
@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {httpSecurity.authorizeRequests(authorize -> authorize.anyRequest() //对所有请求开启授权保护.authenticated() //已认证的请求会自动授权).formLogin(//Customizer.withDefaults()form -> form.loginPage("/login").permitAll()//无需授权就能访问.usernameParameter("name").passwordParameter("pass").successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理.failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理);//使用表单授权方式//.httpBasic(Customizer.withDefaults());//使用基本授权方式httpSecurity.csrf(csrf -> csrf.disable());//关闭csrf功能return httpSecurity.build();}

1.4、用户注销处理 

public class MyLogoutSuccessHandler implements LogoutSuccessHandler {@Overridepublic void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {HashMap map = new HashMap<>();map.put("code",200);map.put("message","注销成功");//将信息json化String jsonString = JSON.toJSONString(map);//返回json数据到前端response.setContentType("application/json;charset=UTF-8");response.getWriter().println(jsonString);}
}
@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {httpSecurity.authorizeRequests(authorize -> authorize.anyRequest() //对所有请求开启授权保护.authenticated() //已认证的请求会自动授权);httpSecurity.formLogin(//Customizer.withDefaults()//使用表单授权方式//.httpBasic(Customizer.withDefaults());//使用基本授权方式form -> form.loginPage("/login").permitAll()//无需授权就能访问.usernameParameter("name").passwordParameter("pass").successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理.failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理);httpSecurity.logout(logout ->logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理);httpSecurity.csrf(csrf -> csrf.disable());//关闭csrf功能return httpSecurity.build();}

1.5、请求未认证处理 

public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {String localizedMessage = authException.getLocalizedMessage();HashMap map = new HashMap<>();map.put("code",400);map.put("message",localizedMessage);//将信息json化String jsonString = JSON.toJSONString(map);//返回json数据到前端response.setContentType("application/json;charset=UTF-8");response.getWriter().println(jsonString);}
}
@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {httpSecurity.authorizeRequests(authorize -> authorize.anyRequest() //对所有请求开启授权保护.authenticated() //已认证的请求会自动授权);httpSecurity.formLogin(//Customizer.withDefaults()//使用表单授权方式//.httpBasic(Customizer.withDefaults());//使用基本授权方式form -> form.loginPage("/login").permitAll()//无需授权就能访问.usernameParameter("name").passwordParameter("pass").successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理.failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理);httpSecurity.logout(logout ->logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理);httpSecurity.exceptionHandling(exception ->exception.authenticationEntryPoint(new MyAuthenticationEntryPoint()));//请求未认证处理httpSecurity.csrf(csrf -> csrf.disable());//关闭csrf功能return httpSecurity.build();}

1.6、跨域处理 

httpSecurity.cors(Customizer.withDefaults());//跨域处理

1.7、用户认证信息处理 

@RestController
public class IndexController {@GetMapping("/")public Map index(){SecurityContext context = SecurityContextHolder.getContext();Authentication authentication = context.getAuthentication();Object principal = authentication.getPrincipal();Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();HashMap map = new HashMap<>();map.put("principal",principal);map.put("权限",authorities);return map;}
}

1.8、会话并发处理 

public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {@Overridepublic void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {HashMap map = new HashMap<>();map.put("code",400);map.put("message","账号已在其他地方登录");//将信息json化String jsonString = JSON.toJSONString(map);HttpServletResponse response = event.getResponse();//返回json数据到前端response.setContentType("application/json;charset=UTF-8");response.getWriter().println(jsonString);}
}
 @Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {httpSecurity.sessionManagement(session ->session.maximumSessions(1).expiredSessionStrategy(new MySessionInformationExpiredStrategy()));//会话并发处理httpSecurity.cors(Customizer.withDefaults());//跨域处理httpSecurity.authorizeRequests(authorize -> authorize.anyRequest() //对所有请求开启授权保护.authenticated() //已认证的请求会自动授权);httpSecurity.formLogin(//Customizer.withDefaults()//使用表单授权方式//.httpBasic(Customizer.withDefaults());//使用基本授权方式form -> form.loginPage("/login").permitAll()//无需授权就能访问.usernameParameter("name").passwordParameter("pass").successHandler(new MyAuthenticationSuccessHandler())//认证成功的处理.failureHandler(new MyAuthenticationFailureHandler())//认证失败的处理);httpSecurity.logout(logout ->logout.logoutSuccessHandler(new MyLogoutSuccessHandler())//用户注销成功处理);httpSecurity.exceptionHandling(exception ->exception.authenticationEntryPoint(new MyAuthenticationEntryPoint()));//请求未认证处理httpSecurity.csrf(csrf -> csrf.disable());//关闭csrf功能return httpSecurity.build();}

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【python】python股票量化交易策略分析可视化(源码+数据集+论文)【独一无二】

&#x1f449;博__主&#x1f448;&#xff1a;米码收割机 &#x1f449;技__能&#x1f448;&#xff1a;C/Python语言 &#x1f449;公众号&#x1f448;&#xff1a;测试开发自动化【获取源码商业合作】 &#x1f449;荣__誉&#x1f448;&#xff1a;阿里云博客专家博主、5…

【fastapi+mongodb】使用motor操作mongodb(三)

本篇文章介绍mongodb的删和改&#xff0c;下面是前两篇文章的链接&#xff1a; 【fastapimongodb】使用motor操作mongodb 【fastapimongodb】使用motor操作mongodb&#xff08;二&#xff09; delete delete 的用法基本和查找一致&#xff0c;包括delete_one&#xff08;删除…

借助AI快速提高英语听力:如何获得适合自己的听力材料?

英语听力是英语学习中的一个重要组成部分&#xff0c;它对于提高语言理解和交流能力至关重要。可理解性学习&#xff08;comprehensible input&#xff09;是语言习得理论中的一个概念&#xff0c;由语言学家Stephen Krashen提出&#xff0c;指的是学习者在理解语言输入的同时&…

时空预测 | 基于深度学习的碳排放时空预测模型

时空预测 模型描述 数据收集和准备&#xff1a;收集与碳排放相关的数据&#xff0c;包括历史碳排放数据、气象数据、人口密度数据等。确保数据的质量和完整性&#xff0c;并进行必要的数据清洗和预处理。 特征工程&#xff1a;根据问题的需求和领域知识&#xff0c;对数据进行…

Canvas绘制图片和区域

如何使用Canvas在图片上绘制区域&#xff1f; 一. 首先&#xff0c;我们需要初始化三个canvas画布&#xff08;初始化Canvas&#xff09; initCanvas() {// 初始化canvas画布let canvasWrap document.getElementsByClassName("canvas-wrap");this.wrapWidth canva…

Android中如何动态的调整Dialog的背景深暗

本文首发于公众号“AntDream”&#xff0c;欢迎微信搜索“AntDream”或扫描文章底部二维码关注&#xff0c;和我一起每天进步一点点 在 Android 开发中&#xff0c;当你使用 Dialog 或 DialogFragment 时&#xff0c;可以通过设置 Window 的背景变暗来突出它的可见性。这个效果…

【密码学】分组密码

文章目录 分组密码的模式分组密码与流密码模式明文分组与密文分组 ECB模式ECB定义ECB特点对ECB模式的攻击改变分组顺序攻击 CBC模式CBC定义初始化向量IVCBC特点对CBC模式的攻击对初始向量进行反转攻击填充提示攻击 CFB模式CFB定义对CFB模式的攻击重放攻击 OFB模式OFB定义CFB模式…

【LocalAI】(13):LocalAI最新版本支持Stable diffusion 3,20亿参数图像更加细腻了,可以继续研究下

最新版本v2.17.1 https://github.com/mudler/LocalAI/releases Stable diffusion 3 You can use Stable diffusion 3 by installing the model in the gallery (stable-diffusion-3-medium) or by placing this YAML file in the model folder: Stable Diffusion 3 Medium 正…

PriorityQueue详解(含动画演示)

目录 PriorityQueue详解1、PriorityQueue简介2、PriorityQueue继承体系3、PriorityQueue数据结构PriorityQueue类属性注释完全二叉树、大顶堆、小顶堆的概念☆PriorityQueue是如何利用数组存储小顶堆的&#xff1f;☆利用数组存储完全二叉树的好处&#xff1f; 4、PriorityQueu…

React AntDesign Layout组件布局刷新页面错乱闪动

大家最近在使用React AntDesign Layout组件布局后刷新页面时&#xff0c;页面布局错乱闪动 经过组件属性的研究才发现&#xff0c;设置 hasSider 为 true 就能解决上面的问题&#xff0c;耽搁了半天的时间&#xff0c;接着踩坑接着加油&#xff01;&#xff01;&#xff01; …

pytorch实现的面部表情识别

一、绪论 1.1 研究背景 面部表情识别 (Facial Expression Recognition ) 在日常工作和生活中&#xff0c;人们情感的表达方式主要有&#xff1a;语言、声音、肢体行为&#xff08;如手势&#xff09;、以及面部表情等。在这些行为方式中&#xff0c;面部表情所携带的表达人类…

SQL找出所有员工当前薪水salary情况

系列文章目录 文章目录 系列文章目录前言 前言 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站&#xff0c;这篇文章男女通用&#xff0c;看懂了就去分享给你的码吧。 描述 有一个薪水表…

Debian Linux安装minikubekubectl

minikube&kubectl minkube用于在本地开发环境中快速搭建一个单节点的Kubernetes集群,还有k3s&#xff0c;k3d&#xff0c;kind都是轻量级的k8skubectl是使用K8s API 与K8s集群的控制面进行通信的命令行工具 这里使用Debian Linux演示&#xff0c;其他系统安装见官网,首先…

使用SpringCache实现Redis缓存

目录 一 什么是Spring Cache 二 Spring Cache 各注解作用 ①EnableCaching ②Cacheable ③CachePut ④CacheEvict 三实现步骤 ①导入spring cache依赖和Redis依赖 ②配置Redis连接信息 ③在启动类上加上开启spring cache的注解 ④ 在对应的方法上加上需要的注解 一 什么…

green bamboo snake

green bamboo snake 【竹叶青蛇】 为什么写这个呢&#xff0c;因为回县城听说邻居有人被蛇咬伤&#xff0c;虽然不足以危及生命&#xff0c;严重的送去市里了。 1&#xff09;这种经常都是一动不动&#xff0c;会躲在草地、菜地的菜叶里面、果树上、有时候会到民房大厅休息&a…

Qt——系统

目录 概述 事件 鼠标事件 进入、离开事件 按下事件 释放事件 双击事件 移动事件 滚轮事件 按键事件 单个按键 组合按键 定时器 QTimerEvent QTimer 窗口事件 文件 输入输出设备 文件读写类 文件和目录信息类 多线程 常用API 线程安全 互斥锁 条件变量…

光纤传感器十大品牌

十大光纤传感器品牌-光纤光栅传感器厂家哪家好-Maigoo品牌榜

【chatgpt】train_split_test的random_state

在使用train_test_split函数划分数据集时&#xff0c;random_state参数用于控制随机数生成器的种子&#xff0c;以确保划分结果的可重复性。这样&#xff0c;无论你运行多少次代码&#xff0c;只要使用相同的random_state值&#xff0c;得到的训练集和测试集划分就会是一样的。…

导入别人的net文件报红问题sdk

1. 使用cmd命令 dotnet --info 查看自己使用的SDK版本 2.直接找到项目中的 global.json 文件&#xff0c;右键打开&#xff0c;直接修改版本为本机的SDK版本&#xff0c;就可以用了

使用Flink CDC实时监控MySQL数据库变更

在现代数据架构中&#xff0c;实时数据处理变得越来越重要。Flink CDC&#xff08;Change Data Capture&#xff09;是一种强大的工具&#xff0c;可以帮助我们实时捕获数据库的变更&#xff0c;并进行处理。本文将介绍如何使用Flink CDC从MySQL数据库中读取变更数据&#xff0…