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

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();}

相关文章:

  • 免费AI绘画工具
  • SpringBoot整合Swagger页面如何禁止访问swagger-ui.html
  • 基于JSP的高校毕业生就业满意度调查统计系统
  • 学习周报:文献阅读+Fluent案例+Fluent相关算法学习
  • Linux DNS配置文档
  • iso27001是什么体系,有什么作用?
  • 欢度盛夏,畅享清凉——七月超市营销策略
  • 为什么人们对即将推出的 Go 1.23 迭代器感到愤怒
  • 开关阀(1):定位器与电磁阀的区别
  • HarmonyOS【ArkUI组件--TextInput】
  • AWS无服务器 应用程序开发—第八章 计算服务(AWS Lambda)
  • 一文理清OCR的前世今生
  • 【千帆AppBuilder】你有一封邮件待查收|未来的我,你好吗?欢迎体验AI应用《未来信使》
  • 查看服务器端口,如何查看服务器端口是多少并修改
  • 深度解析“科技信贷”:构建科技支行的五维模型
  • ES6指北【2】—— 箭头函数
  • Cookie 在前端中的实践
  • ES2017异步函数现已正式可用
  • Laravel深入学习6 - 应用体系结构:解耦事件处理器
  • Python_网络编程
  • vue-cli3搭建项目
  • vue学习系列(二)vue-cli
  • 编写符合Python风格的对象
  • 对象管理器(defineProperty)学习笔记
  • 给Prometheus造假数据的方法
  • 构造函数(constructor)与原型链(prototype)关系
  • 技术攻略】php设计模式(一):简介及创建型模式
  • 实习面试笔记
  • 如何在招聘中考核.NET架构师
  • ​软考-高级-系统架构设计师教程(清华第2版)【第20章 系统架构设计师论文写作要点(P717~728)-思维导图】​
  • ​用户画像从0到100的构建思路
  • (1)(1.13) SiK无线电高级配置(六)
  • (32位汇编 五)mov/add/sub/and/or/xor/not
  • (MIT博士)林达华老师-概率模型与计算机视觉”
  • (补充):java各种进制、原码、反码、补码和文本、图像、音频在计算机中的存储方式
  • (超详细)2-YOLOV5改进-添加SimAM注意力机制
  • (二开)Flink 修改源码拓展 SQL 语法
  • (附源码)springboot码头作业管理系统 毕业设计 341654
  • (南京观海微电子)——I3C协议介绍
  • (切换多语言)vantUI+vue-i18n进行国际化配置及新增没有的语言包
  • (十六)视图变换 正交投影 透视投影
  • (十七)devops持续集成开发——使用jenkins流水线pipeline方式发布一个微服务项目
  • (转)如何上传第三方jar包至Maven私服让maven项目可以使用第三方jar包
  • .NET 5种线程安全集合
  • .net core 微服务_.NET Core 3.0中用 Code-First 方式创建 gRPC 服务与客户端
  • .NET NPOI导出Excel详解
  • .net 按比例显示图片的缩略图
  • .NET/C# 的字符串暂存池
  • .NET/C# 使窗口永不获得焦点
  • .NET/C#⾯试题汇总系列:⾯向对象
  • .netcore 如何获取系统中所有session_如何把百度推广中获取的线索(基木鱼,电话,百度商桥等)同步到企业微信或者企业CRM等企业营销系统中...
  • .Net开发笔记(二十)创建一个需要授权的第三方组件
  • .NET是什么
  • .NET值类型变量“活”在哪?
  • .NET中的Event与Delegates,从Publisher到Subscriber的衔接!