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 {
    @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.mfbz.cn/a/714477.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

工程设计问题---多盘离合器制动器设计问题

这个问题的主要目的是使多片式离合器制动器的质量最小化。在这个问题中&#xff0c;使用了五个整数决策变量&#xff0c;它们是内半径&#xff08;x1&#xff09;、外半径&#xff08;x2&#xff09;、盘厚度&#xff08;x3&#xff09;、致动器的力&#xff08;x4&#xff09;…

QT属性系统,简单属性功能快速实现 QT属性的简单理解 属性学习如此简单 一文就能读懂QT属性 QT属性最简单的学习

4.4 属性系统 Qt 元对象系统最主要的功能是实现信号和槽机制&#xff0c;当然也有其他功能&#xff0c;就是支持属性系统。有些高级语言通过编译器的 __property 或者 [property] 等关键字实现属性系统&#xff0c;用于提供对成员变量的访问权限&#xff0c;Qt 则通过自己的元对…

mysql-connector下载教程(手把手)

下载一个第三方库主要有三种途径&#xff1a; 去官方网站 Oracle 官网去github去Maven中央仓库 前两个方法比较麻烦&#xff0c;你还需要去找。 这里就只介绍maven的方法 Maven类似于手机app的应用商店。 操作步骤&#xff1a; 点击右边进入官网Maven中央仓库 在搜索框中…

NetSuite Saved Search 之 Filter By Summary

在某些业务场景中&#xff0c;用户需要一个TOP X的报表。例如&#xff0c;过去一段时间内&#xff0c;最多数量的事务处理类型。这就需要利用Saved Search中的Filter By Summary功能。 这在Criteria下的Summary页签里可以定义。其作用是对Result中Summary类型的结果进行过滤。也…

揭秘最强气象武器的库,SPEI-Python不可思议之处.

spei-python是一个专门用于计算标准化降水蒸散指数&#xff08;Standardized Precipitation Evapotranspiration Index,SPEI&#xff09;的Python库.SPEI是一种综合考虑降水和潜在蒸散发的干旱指数,用于评估干旱的严重程度和持续时间. 安装 ## 可以使用 pip 来安装 spei-pyth…

Proteus 新建工程

Proteus 新建工程 新建简单工程 首先在File工具栏中点击New Project&#xff0c;弹出新建工程向导程序(New Proteus Wizard) 填写工程名称与存储路径&#xff0c;选择New Proteus并点击Next进行下一步设置 我们不需要生成PCB文件&#xff0c;一路默认&#xff0c;点击Next即…

安装Docker Desktop报错WSL 2 installation is incomplete(实操教程)

点击运行提示WSL2安装不完整问题描述&#xff1a;WSL 2 installation is incomplete. The WSL 2 Linux kernel is now installed using a separate MSl updatepackage. Please click the link and follow the instructions to install thekernel update: https://aka.ms/wsl2ke…

SpringBoot接入RS-232串口通讯实现数据交互

目录 一、什么是RS-232&#xff1f; 先看看硬件通讯接口长啥样 RS-232 二、方案一 1.前期准备 a.配置 RXTX 1&#xff09;下载 RXTX 包并解压 2&#xff09;拷贝动态库到对应的jdk目录下 Windows平台 Linux平台 3&#xff09;在工程根目录下创建 lib 文件夹&#x…

【机器学习】机器学习与教育科技在个性化教学中的融合应用与性能优化新探索

文章目录 引言机器学习与教育科技的基本概念机器学习概述监督学习无监督学习强化学习 教育科技概述学生学习行为分析个性化学习路径推荐智能化教育评估 机器学习与教育科技的融合应用实时学习数据分析数据预处理特征工程 学生成绩预测与优化模型训练模型评估 个性化学习路径推荐…

盛世古董乱世金-数据库稳定到底好不好?

是不是觉得这个还用问&#xff1f; 是的要问。因为这个还是一个有争议的问题。但是争议双方都没有错。这就像辩论&#xff0c;有正反双方。大家都说的有道理&#xff0c;但是很难说谁对谁错。 正方观点&#xff1a;数据库稳定好 其实这个是用户的观点&#xff0c;应用开发人…

Docker:在DockerHub上创建私有仓库

文章目录 Busybox创建仓库推送镜像到仓库 本篇开始要学习在DockerHub上搭建一个自己的私有仓库 Busybox Busybox是一个集成了三百多个最常用Linux命令和工具的软件&#xff0c;BusyBox包含了很多工具&#xff0c;这里拉取该镜像推送到仓库中&#xff1a; 安装 apt install …

USB转I2C转SPI芯片CH341与CH347比较

1. 芯片中文资料&#xff1a; USB转I2C转SPI芯片CH341 高速USB转接芯片CH347转9M双串口转I2C转SPI转JTAG转SWD USB2.0高速转接芯片CH347应用开发手册 2. CH341与CH347比较&#xff1a; 类别CH341CH347备注串口速度2M9MCH347的串口速度更快设置CH341的I2C或SPI不能与串口同…

Matlab电话按键拨号器设计

前言 这篇文章是目前最详细的 Matlab 电话按键拨号器设计开源教程。如果您在做课程设计或实验时需要参考本文章&#xff0c;请注意避免与他人重复&#xff0c;小心撞车。博主做这个也是因为实验所需&#xff0c;我在这方面只是初学者&#xff0c;但实际上&#xff0c;从完全不…

【chatbot-api开源项目】开发文档

chatbot-api 1. 需求分析1-1. 需求分析1-2. 系统流程图 2. 技术选型3. 项目开发3-1. 项目初始化3-2. 爬取接口获取问题接口回答问题接口创建对应对象 3-3. 调用AI3-4. 定时自动化回答 4. Docker部署5. 扩展5-1. 如果cookie失效了怎么处理5-2. 如何更好的对接多个回答系统 Gitee…

Web渗透信息收集进阶

网站敏感目录与文件 网站敏感目录表示网站目录中容易被恶意人员利用的一些目录。通常恶意人员都是通过工具扫描&#xff0c;来扫出网站的敏感目录&#xff0c;敏感目录是能够得到其他网页的信息&#xff0c;从而找到后台管理页面&#xff0c;尝试进入后台等&#xff0c;扫描网…

在Ubuntu中创建Ruby on Rails项目并搭建数据库

新建Rails项目 先安装bundle Ruby gem依赖项工具&#xff1a; sudo apt install bundle 安装Node.js: sudo apt install nodejs 安装npm 包管理器&#xff1a; sudo apt install npm 安装yarn JavaScript包管理工具&#xff1a; sudo apt install yarn 安装webpacker: …

leetcode236. 二叉树的最近公共祖先

一、题目描述&#xff1a; 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 二、输入输出实例&#xff1a; 示例 1&#xff1a; 输入&#xff1a;root [3,5,1,6,2,0,8,null,null,7,4], p 5, q 1 输出&#xff1a;3 解释&#xff1a;节点 5 和节点 1 的最近公共祖先…

Ps:脚本事件管理器

Ps菜单&#xff1a;文件/脚本/脚本事件管理器 Scripts/Script Events Manager 脚本事件管理器 Script Events Manager允许用户将特定的事件&#xff08;如打开、存储或导出文件&#xff09;与 JavaScript 脚本或 Photoshop 动作关联起来&#xff0c;以便在这些事件发生时自动触…

按键输入消抖

按键输入是人机对话不可缺少的一部分&#xff0c;对于消抖设计&#xff0c;一种是软件消抖&#xff0c;一种是硬件消抖。但在单片机电路设计中&#xff0c;采用电容消抖才是最佳的选择&#xff0c;其次才是定时器消抖。 1、按键输入采用软件消抖 1)、通过定时器方式定时读取按…

【Android面试八股文】请你描述一下JVM的内存模型

文章目录 JVM内存模型1. 方法区(Method Area)运行时常量池(Runtime Constant Pool)2. 堆(Heap)3. 栈(Stack)4. 本地方法栈(Native Method Stack)5. 程序计数器(Program Counter Register)6. 直接内存(Direct Memory)JVM内存溢出的情况Java的口号是: “Write onc…