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

news2024/10/5 19:14:46

目录

一、实现前后端分离

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 {
    @Override
    public 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);
    }
}
@Bean
    public 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 {
    @Override
    public 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);
    }
}
@Bean
    public 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 {
    @Override
    public 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);
    }
}
@Bean
    public 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 {
    @Override
    public 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);
    }
}
@Bean
    public 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 {
    @Override
    public 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);
    }
}
 @Bean
    public 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.coloradmin.cn/o/1828455.html

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

相关文章

ComfyUI

文章目录 一、关于 ComfyUI特点快捷键QA你为什么做这个&#xff1f;这是给谁的&#xff1f; 二、安装1、Windows直接链接下载如何在另一个UI和ComfyUI之间共享模型&#xff1f; 2、Jupyter Notebook3、手动安装&#xff08;Windows、Linux&#xff09;AMD GPU&#xff08;仅Lin…

MEMS:Lecture 18 Feedback

讲义 Linear feedback MEMS热板 Hotplate MEMS&#xff08;微机电系统&#xff09;热板是现代气体传感器的重要组成部分。它们通过加热一种活性材料来工作&#xff0c;这种材料与气体发生反应&#xff0c;从而改变其电阻。电阻的变化可以用来检测和测量特定气体的存在和浓度。…

讨论C++模板

讨论C模板 函数重载和泛型编程模板分类函数模板语法原理函数模板的实例化隐式实例化显示实例化 匹配原则 类模板语法类模板的实例化 C支持了函数重载&#xff0c;通过函数名相同&#xff0c;参数列表不同来构成函数重载&#xff0c;以达到方便程序员调用。但还是没有改变代码大…

软考初级网络管理员__操作系统单选题

1.使用Windows提供的网络管理命令(请作答此空)可以查看本机的路由表&#xff0c;()可以修改本机的路由表。 tracert arp ipconfig netstat 2.在Windows 的命令行窗口中键入命令C:\>nslookupset type MX>202.30.192.2这个命令序列的作用是查询()。 邮件服务器信息 …

【鸿蒙 HarmonyOS】Swiper组件

一、背景 项目中通常会遇到图片轮播&#xff0c;内容轮播的场景&#xff1b;如&#xff1a;在一些应用首页显示推荐的内容时&#xff0c;需要用到轮播显示的能力。 二、源码地址 ✍Gitee开源项目地址&#x1f449;&#xff1a;https://gitee.com/cheinlu/harmony-os-next-swi…

【Linux】进程_5

文章目录 五、进程6. 进程的调度和转换7. 环境变量 未完待续 五、进程 6. 进程的调度和转换 进程在运行过程中&#xff0c;要产生大量的临时数据&#xff0c;存放在CPU的寄存器中&#xff0c;CPU内部的所有临时数据我们叫做进程的 硬件上下文。当进程的时间片到了时&#xff…

用LoRA微调 Llama 2:定制大型语言模型进行问答

Fine-tune Llama 2 with LoRA: Customizing a large language model for question-answering — ROCm Blogs (amd.com) 在这篇博客中&#xff0c;我们将展示如何在AMD GPU上使用ROCm对Llama 2进行微调。我们采用了低秩适配大型语言模型(LoRA)来克服内存和计算限制&#xff0c;…

【百度之星】题目练手

BD202301公园 码题集OJ-公园 (matiji.net) 看到之后就想到之前没写出来的一道cf题目&#xff0c;因为不敢打暴力导致没写出来hhh~ 首先&#xff0c;这个问题贪心必有反例&#xff08;贪心两个人尽早相遇&#xff09; 数据范围40000&#xff0c; 直接暴力枚举两个人在哪个点相遇…

云原生技术实现Devops自动化运维

云原生技术实现Devops自动化运维 随着云计算和DevOps理念的普及&#xff0c;云原生技术在自动化运维中的应用日益广泛。本文将探讨云原生技术如何通过容器化、微服务架构、CI/CD流水线等手段&#xff0c;提升DevOps自动化运维的效率和灵活性&#xff0c;并通过案例分析具体应用…

Linux screen命令使用

文章目录 1. 前言2. screen是什么?3. screen使用场景描述3. screen常用命令4. 小结5. 参考 1. 前言 实际开发中用到的云服务器&#xff0c;如果项目使用的是python&#xff0c;需要利用项目运行一些时间较长的项目程序脚本的话&#xff0c;由于我们通过ssh连接远端服务器&…

【面经总结】Java集合 - Map

Map 概述 Map 架构 HashMap 要点 以 散列(哈希表) 方式存储键值对&#xff0c;访问速度快没有顺序性允许使用空值和空键有两个影响其性能的参数&#xff1a;初始容量和负载因子。 初始容量&#xff1a;哈希表创建时的容量负载因子&#xff1a;其容量自动扩容之前被允许的最大…

2024年【山东省安全员A证】考试资料及山东省安全员A证试题及解析

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 山东省安全员A证考试资料是安全生产模拟考试一点通总题库中生成的一套山东省安全员A证试题及解析&#xff0c;安全生产模拟考试一点通上山东省安全员A证作业手机同步练习。2024年【山东省安全员A证】考试资料及山东省…

黑马程序员Springboot2简单学习笔记

Session是用于存放用户与web服务器之间的会话&#xff0c;即服务器为客户端开辟的存储空间。 文章&#xff1a;lombok Slf4j注解 Slf4j是用作日志输出的&#xff0c;一般会在项目每个类的开头加入该注解 可以配置静态资源的访问路径 这样访问任何的静态资源 但是每个页面都得…

20. mediasoup服务器的布署与使用

Mediasoup Demo部署 架构服务分析 服务端提供3个服务&#xff1a; 1.www服务&#xff0c;浏览器通过访问服务器目录获取客户端代码&#xff0c;通过V8引擎&#xff0c;启动底层WebRTC 2.nodejs提供websocket服务和http服务&#xff0c;用于信令交互 3.Mediasoup C提供的流媒体…

Ui学习--UITableView

UI学习 UITableView基础UITableView协议UITableView高级协议与单元格总结 UITableView基础 UITableView作为iOS中的一个控件&#xff0c;用于以表格形式展示数据。例如通讯录好友&#xff0c;朋友圈信息等&#xff0c;都是UITableView的实际运用场景。 首先我们先要加入两个协…

ARM32开发--电源管理单元

知不足而奋进 望远山而前行 目录 文章目录 前言 学习目标 学习内容 PMU 电源域 VDD/VDDA域 备份域 1.2V域 省电模式 睡眠模式 深度睡眠模式 待机模式 几种模式总结 WFI和WFE指令 案例需求 模式初始化 源码 总结 前言 在嵌入式系统中&#xff0c;有效的电池管…

使用kettle做的数据同步案例

1 mongo同步数据到mysql中 我想把51万8400的计算出来的八字信息&#xff0c;从mongo同步到mysql&#xff0c;看看在mysql中运行会怎么样。 选择mongodb input&#xff0c;这个是在Big Data中。 填写数据库和表 获取到mongodb的字段,获取到mongo的字段&#xff0c;如果某个字段…

Windows10 利用QT搭建SOEM开发环境

文章目录 一. SOEM库简介二. 安装WinPcap三. SOEM(1.4)库安装(1) 编译32位库(2) 编译64位库 四. 运行SOEM示例代码五. WIN10下利用QT构建SOEM开发环境 一. SOEM库简介 SOEM&#xff08;Scalable Open EtherCAT Master 或 Simple Open EtherCAT Master&#xff09;是一个开源的…

SwiftUI 6.0(iOS 18)新容器视图修改器漫谈

概览 本届 WWDC 2024 观影正如火如荼的进行中&#xff0c;一片鸟语花香、枝繁叶茂的苹果树上不时结出几颗令人垂涎欲滴的美味苹果让秃头码农们欲罢不能。 如您所愿&#xff0c;在界面布局“利器” SwiftUI 这根蔓藤也长出不少喜人的果实&#xff0c;其中在 iOS 18.0 中新添加的…

1949年到2021年中国历年稻谷产量统计报告

数据介绍 数据来源于国家统计局&#xff0c;为1949年到2021年我国每年的稻谷产量数据。 2021年&#xff0c;我国稻谷产量为21284.24万吨&#xff0c;比上年增长0.5%。 数据统计单位为&#xff1a;万吨 我国稻谷产量有多少&#xff1f; 2021年&#xff0c;我国稻谷产量为2128…